Automatic registry design-pattern for mapping names to functionality.
Project description
AutoRegistry
Invoking functions and class-constructors from a string is a common design pattern that autoregistry aims to solve. For example, a user might specify a backend of type "sqlite" in a yaml configuration file, for which our program needs to construct the SQLite subclass of our Database class. Classically, you would need to manually create a lookup mapping the string "sqlite" to the SQLite constructor. With autoregistry, the lookup is autmatically created for you.
autoregistry has a single powerful class Registry that can do the following:
Be subclassed to automatically register subclasses by their name.
Be directly invoked my_registery = Registry() to create a decorator for registering callables like functions.
Installation
AutoRegistry requires Python >=3.8.
python -m pip install autoregistry
Examples
Class Inheritence
Registry adds a dictionary-like interface to class constructors for looking up subclasses.
from dataclasses import dataclass
from autoregistry import Registry, abstractmethod
@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
class SurfingPikachu(Pikachu):
def attack(self, target):
return 3
print(f"{len(Pokemon)} Pokemon registered:")
print(f" {list(Pokemon)}")
charmander = Pokemon["cHaRmAnDer"](
level=7, hp=31
) # By default, lookup is case-insensitive
print(f"Created Pokemon: {charmander}")
This code block produces the following output:
3 Pokemon registered:
['charmander', 'pikachu', 'surfingpikachu']
Created Pokemon: Charmander(level=7, hp=31)
Function Registry
Directly instantiating a Registry object allows you to register functions by decorating them.
from autoregistry import Registry
pokeballs = Registry()
@pokeballs
def masterball(target):
return 1.0
@pokeballs
def pokeball(target):
return 0.1
for ball in ["pokeball", "masterball"]:
success_rate = pokeballs[ball](None)
print(f"Ash used {ball} and had {success_rate=}")
This code block produces the following output:
Ash used pokeball and had success_rate=0.1
Ash used masterball and had success_rate=1.0
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for autoregistry-0.2.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | b7f62427fa8267f9c35d674adc584f968c7257e6cec379fe6d9bd89c363f6e65 |
|
MD5 | 9ce7ace5dcaf4ea5fa7eaa4efbd8bf68 |
|
BLAKE2b-256 | 3e0d3628471ebe4388951fdd857df5b430ddcd0ba1de7057d2fb333bfb5895ae |