API Documentation
- class_registry.base.AutoRegister(registry: BaseMutableRegistry[T]) type
Creates a base class that automatically registers all non-abstract subclasses in the specified registry.
Example:
commands = ClassRegistry(attr_name='command_name') class BaseCommand(AutoRegister(commands), ABC): @abstractmethod def exec(self): raise NotImplementedError() class PrintCommand(BaseCommand): command_name = 'print' def exec(self): ... print(list(commands.items())) # [('print', PrintCommand)]
Important
Python defines abstract as “having at least one unimplemented abstract method”; adding
abc.ABCas a base class is not enough.- Parameters:
registry –
The registry that new classes will be added to.
Note
The registry’s
attr_nameattribute must be set.
- class class_registry.base.BaseMutableRegistry(attr_name: str | None = None)
Extends
BaseRegistrywith methods that can be used to modify the registered classes.- Parameters:
attr_name – If provided,
register()will automatically detect the key to use when registering new classes.
- items() Iterable[tuple[Hashable, Type[T]]]
Warning
DEPRECATED: use
keys()orclasses()instead.Returns the collection of registered key-class pairs, in the order that they were registered.
- keys() Iterable[Hashable]
Returns the collection of registry keys, in the order that they were registered.
- register(key: D, /) D
- register(key: Hashable) Callable[[D], D]
Decorator that registers a class with the registry.
Example:
registry = ClassRegistry(attr_name='widget_type') @registry.register class CustomWidget(BaseWidget): widget_type = 'custom' ... # Override the registry key: @registry.register('premium') class AdvancedWidget(BaseWidget): ...
- Parameters:
key – The registry key to use for the registered class. Optional if the registry’s
attr_nameis set.
- class class_registry.base.BaseRegistry
Base functionality for registries.
- static create_instance(class_: Type[T], *args: Any, **kwargs: Any) T
Prepares the return value for
get().You may override this method in a subclass, if you want to customize the way new instances are created.
- static gen_lookup_key(key: Hashable) Hashable
Used by
get()to generate a lookup key.You may override this method in a subclass, for example if you need to support legacy aliases, etc.
- Parameters:
key – The key value provided to e.g.,
__getitem__()- Returns:
The registry key, used to look up the corresponding class.
- get(key: Hashable, *args: Any, **kwargs: Any) T
Creates a new instance of the class matching the specified key.
- Parameters:
key – The corresponding load key.
args – Positional arguments passed to class initializer. Ignored if the class registry was initialized with a null template function.
kwargs – Keyword arguments passed to class initializer. Ignored if the class registry was initialized with a null template function.
References
__init__()
- exception class_registry.base.RegistryKeyError
Used to differentiate a registry lookup from a standard KeyError.
This is especially useful when a registry class expects to extract values from dicts to generate keys.
- class class_registry.cache.ClassRegistryInstanceCache(class_registry: ClassRegistry[T], *args: Any, **kwargs: Any)
Wraps a ClassRegistry instance, caching instances as they are created.
This allows you to create [multiple] registries that cache instances locally (so that they can be scoped and garbage-collected), whilst keeping the class registry separate.
Note that the internal class registry is copied by reference, so any classes that are registered afterward are accessible to both the
ClassRegistryand theClassRegistryInstanceCache.- Parameters:
class_registry – The wrapped ClassRegistry.
args – Positional arguments passed to the class registry’s template when creating new instances.
kwargs – Keyword arguments passed to the class registry’s template function when creating new instances.
- get_class_key(key: Hashable) Hashable
Generates a key that can be used to store/lookup values in the wrapped
ClassRegistryinstance.This method is only invoked in the event of a cache miss.
- Parameters:
key – Value provided to
__getitem__().
- get_instance_key(key: Hashable) Hashable
Generates a key that can be used to store/lookup values in the instance cache.
- Parameters:
key – Value provided to
__getitem__().
- property registry: ClassRegistry[T]
Accessor for the wrapped class registry.
- class class_registry.entry_points.EntryPointClassRegistry(group: str, attr_name: str | None = None)
A class registry that loads classes using setuptools entry points.
- Parameters:
group – The name of the entry point group that will be used to load new classes.
attr_name –
If set, the registry will “brand” each class with its corresponding registry key. This makes it easier to perform reverse lookups later.
Note: if a class already defines this attribute, the registry will overwrite it!
- get(key: Hashable, *args: Any, **kwargs: Any) T
Creates a new instance of the class matching the specified key.
- Parameters:
key – The corresponding load key.
args – Positional arguments passed to class initializer. Ignored if the class registry was initialized with a null template function.
kwargs – Keyword arguments passed to class initializer. Ignored if the class registry was initialized with a null template function.
References
__init__()
- class class_registry.patcher.RegistryPatcher(registry: BaseMutableRegistry[T], *args: Type[T], **kwargs: Type[T])
Creates a context in which classes are temporarily registered with a class registry, then removed when the context exits.
Note
Only mutable registries can be patched.
- Parameters:
registry – A
MutableRegistryinstance to patch.args –
Classes to add to the registry.
This behaves the same as decorating each class with
@registry.register.Note
registry.attr_namemust be set.kwargs –
Same as
args, except you explicitly specify the registry keys.In the event of a conflict, values in
argsoverride values inkwargs.
- class DoesNotExist
Used to identify a value that did not exist before we started.
- class class_registry.registry.ClassRegistry(attr_name: str | None = None, unique: bool = False)
Maintains a registry of classes and provides a generic factory for instantiating them.
- Parameters:
attr_name – If provided,
register()will automatically detect the key to use when registering new classes.unique –
Determines what happens when two classes are registered with the same key:
True: AKeyErrorwill be raised.False: The second class will replace the first one.
- class class_registry.registry.SortedClassRegistry(sort_key: Any, attr_name: str | None = None, unique: bool = False, reverse: bool = False)
A ClassRegistry that uses a function to determine sort order when iterating.
- Parameters:
sort_key –
Attribute name or callable, used to determine the sort value.
If callable, must accept two tuples of (key, class, lookup_key).
You can also use
functools.cmp_to_key().attr_name – If provided,
register()will automatically detect the key to use when registering new classes.unique –
Determines what happens when two classes are registered with the same key:
True: The second class will replace the first one.False: AValueErrorwill be raised.
reverse – Whether to reverse the sort ordering.