Skip to content

Instantly share code, notes, and snippets.

@davidlj95
Last active August 27, 2018 13:39
Show Gist options
  • Save davidlj95/e3028ca87d598bb624797f840efc08b7 to your computer and use it in GitHub Desktop.
Save davidlj95/e3028ca87d598bb624797f840efc08b7 to your computer and use it in GitHub Desktop.
Python 3: Class registry
"""Implements a class registry based on its name using Python 3 metaclasses
**Source:**
- https://effectivepython.com/2015/02/02/\
register-class-existence-with-metaclasses/
"""
REGISTRY = {}
"""
dict: maps the class name into the actual class
"""
class ClassRegistry(type):
"""Saves in the registry each class by its name."""
def __new__(mcs, name, bases, class_dict):
cls = type.__new__(mcs, name, bases, class_dict)
REGISTRY[cls.__name__] = cls
return cls
class BaseClass:
"""Base class every registered class inherits from."""
pass
class RegisteredClass(BaseClass, metaclass=ClassRegistry):
"""RegisteredClass accessible from registry upon creation."""
pass
@davidlj95
Copy link
Author

davidlj95 commented Aug 27, 2018

Class registry with Python 3

Used in bitcoin-framework for Opcode deserialization.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment