def__setitem__(self, key, value): ifnotcallable(value): raise Exception(f"Value of a Registry must be a callable!\nValue: {value}") if key isNone: key = value.__name__ if key inself._dict: logging.warning("Key %s already in registry %s." % (key, self._name)) self._dict[key] = value
defregister(self, target): """Decorator to register a function or class."""
defadd(key, value): self[key] = value return value
def_handle_errors(errors): """Log out and possibly reraise errors during import.""" ifnot errors: return for name, err in errors: logging.warning("Module {} import failed: {}".format(name, err))
defimport_all_modules_for_register(custom_module_paths=None): """Import all modules for register.""" modules = [] for base_dir, modules in ALL_MODULES: for name in modules: full_name = base_dir + "." + name modules.append(full_name) ifisinstance(custom_module_paths, list): modules += custom_module_paths errors = [] for module in modules: try: importlib.import_module(module) except ImportError as error: errors.append((module, error)) _handle_errors(errors)
使用
最后我们使用下我们的注册器模块:
1 2 3 4 5 6
from register import import_all_modules_for_register from register import Registers