Last active
August 27, 2018 13:39
-
-
Save davidlj95/e3028ca87d598bb624797f840efc08b7 to your computer and use it in GitHub Desktop.
Python 3: Class registry
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Class registry with Python 3
Used in bitcoin-framework for Opcode deserialization.