Created
December 16, 2018 07:15
-
-
Save foowaa/186ef11d5299cd51190b27b9edecb4a7 to your computer and use it in GitHub Desktop.
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
_registry_path = Path(__file__).parent / 'registry.json' | |
if _registry_path.exists(): | |
with _registry_path.open(encoding='utf-8') as f: | |
_REGISTRY = json.load(f) | |
else: | |
_REGISTRY = {} | |
def short_name(cls: type) -> str: | |
"""Returns just a class name (without package and module specification).""" | |
return cls.__name__.split('.')[-1] | |
def register(name: str = None) -> type: | |
""" | |
Register classes that could be initialized from JSON configuration file. | |
If name is not passed, the class name is converted to snake-case. | |
""" | |
def decorate(model_cls: type, reg_name: str = None) -> type: | |
model_name = reg_name or short_name(model_cls) | |
global _REGISTRY | |
cls_name = model_cls.__module__ + ':' + model_cls.__name__ | |
if model_name in _REGISTRY and _REGISTRY[model_name] != cls_name: | |
logger.warning('Registry name "{}" has been already registered and will be overwritten.'.format(model_name)) | |
_REGISTRY[model_name] = cls_name | |
return model_cls | |
return lambda model_cls_name: decorate(model_cls_name, name) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment