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.ABC as a base class is not enough.

Parameters:

registry

The registry that new classes will be added to.

Note

The registry’s attr_name attribute must be set.

class class_registry.base.BaseMutableRegistry(attr_name: str | None = None)

Extends BaseRegistry with 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() or classes() 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_name is set.

unregister(key: Hashable) Type[T]

Unregisters the class with the specified key.

Parameters:

key – The registry key to remove (not the registered class!).

Returns:

The class that was unregistered.

Raises:

KeyError – if the key is not registered.

values() Iterable[Type[T]]

Warning

DEPRECATED: use classes() instead.

Returns the collection of registered classes, in the order that they were registered.

class class_registry.base.BaseRegistry

Base functionality for registries.

classes() Iterable[Type[T]]

Returns the collection of registered classes.

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.

Parameters:
  • class – The requested class.

  • args – Positional keywords passed to get().

  • kwargs – Keyword arguments passed to get().

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__()

abstractmethod get_class(key: Hashable) Type[T]

Returns the class associated with the specified key.

abstractmethod keys() Iterable[Hashable]

Returns the collection of registered keys.

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 ClassRegistry and the ClassRegistryInstanceCache.

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 ClassRegistry instance.

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.

warm_cache() None

Warms up the cache, ensuring that an instance is created for every key currently in the registry.

Note

This method has no effect for any classes added to the wrapped ClassRegistry after calling warm_cache.

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__()

get_class(key: Hashable) Type[T]

Returns the class associated with the specified key.

keys() Iterable[Hashable]

Returns the collection of registered keys.

refresh() None

Purges the local cache. The next access attempt will reload all entry points.

This is useful if you load a distribution at runtime…such as during unit tests for phx-class-registry. Otherwise, it probably serves no useful purpose (:

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 MutableRegistry instance to patch.

  • args

    Classes to add to the registry.

    This behaves the same as decorating each class with @registry.register.

    Note

    registry.attr_name must be set.

  • kwargs

    Same as args, except you explicitly specify the registry keys.

    In the event of a conflict, values in args override values in kwargs.

class DoesNotExist

Used to identify a value that did not exist before we started.

apply() None

Applies the new values.

restore() None

Restores previous settings.

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: A KeyError will be raised.

    • False: The second class will replace the first one.

get_class(key: Hashable) Type[T]

Returns the class associated with the specified key.

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: A ValueError will be raised.

  • reverse – Whether to reverse the sort ordering.

static create_sorter(sort_key: str) Callable[[...], SupportsAllComparisons]

Given a sort key, creates a function that can be used to sort items when iterating over the registry.

keys() Iterable[Hashable]

Returns the collection of registry keys, in the order that they were registered.