AutoRegistry
AutoRegistry is a Python library that implements an automatic registry design pattern, enabling the mapping of string names to functionality (classes or functions) without manual lookup dictionaries. It supports inheritance-based registration, decorator-based registration, and module-level traversal for automatic setup. The library is actively maintained with consistent minor and patch releases, currently at version 1.2.1.
Warnings
- gotcha Encountering `KeyCollisionError` during module hot-reloading (e.g., in development environments like IPython with `%autoreload`). This could occur if modules containing registered classes were reloaded, leading to re-registration.
- gotcha When using `autoregistry.pydantic.BaseModel`, registering multiple classes with the same derived name could trigger `KeyCollisionError`.
- gotcha Potential issues when combining `autoregistry.Registry` subclasses with `attrs` decorators, especially when `slots` are enabled, leading to unexpected behavior or errors.
- gotcha Unexpected behavior or incorrect naming due to issues with module registry name preprocessing, potentially leading to incorrect keys in the registry when using module-based registration.
Install
-
pip install autoregistry -
pip install autoregistry[pydantic]
Imports
- Registry
from autoregistry import Registry
- BaseModel
from autoregistry.pydantic import BaseModel
Quickstart
from abc import abstractmethod
from dataclasses import dataclass
from autoregistry import Registry
@dataclass
class Pokemon(Registry):
level: int
hp: int
@abstractmethod
def attack(self, target):
"""Attack another Pokemon."""
class Charmander(Pokemon):
def attack(self, target):
return 1
class Pikachu(Pokemon):
def attack(self, target):
return 2
# Access registered subclasses
charmander = Pokemon["charmander"](level=5, hp=40) # Name is auto-derived from class name
pikachu = Pokemon["pikachu"](level=7, hp=50)
assert charmander.attack(pikachu) == 1
assert isinstance(charmander, Charmander)
assert isinstance(pikachu, Pikachu)
print(f"Created {charmander.__class__.__name__} (Level: {charmander.level}, HP: {charmander.hp})")
print(f"Created {pikachu.__class__.__name__} (Level: {pikachu.level}, HP: {pikachu.hp})")