No project description provided
Project description
AutoRegistry
Invoking functions and class constructors from a string is a common design pattern that autoregistry aims to solve. autoregistry has a single powerful class Registry that can do the following:
- Be subclassed to automatically register subclasses by their name.
Registry is, itself, a subclass of ABC for easy interface creation.
Be directly invoked my_registery = Registry() to create a decorator for registering callables like functions.
Installation
python -m pip install autoregistry
Examples
Class Inheritence
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("")
print(f"{len(Pokemon)} Pokemon registered:")
print(f" {list(Pokemon.keys())}")
# By default, lookup is case-insensitive
charmander = Pokemon["cHaRmAnDer"](level=7, hp=31)
print(f"Created Pokemon: {charmander}")
print("")
This code block produces the following output:
3 Pokemon registered:
['charmander', 'pikachu', 'surfingpikachu']
Created Pokemon: Charmander(level=7, hp=31)
Function Registry
from autoregistry import Registry
pokeballs = Registry()
@pokeballs
def masterball(target):
return 1.0
@pokeballs
def pokeball(target):
return 0.1
print("")
for ball in ["pokeball", "masterball"]:
success_rate = pokeballs[ball](None)
print(f"Ash used {ball} and had {success_rate=}")
print("")
This code block produces the following output:
Ash used pokeball and had success_rate=0.1
Ash used greatball and had success_rate=0.3
Ash used ultraball and had success_rate=0.5
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
autoregistry-0.1.0.tar.gz
(8.6 kB
view hashes)
Built Distribution
Close
Hashes for autoregistry-0.1.0-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 0982c3d45205beca19fb8d8413d2e8e4ad00bdcaabec663312c2c7c74a4b7fe9 |
|
MD5 | 68d6c962a2dd223ade0315f86f9fff12 |
|
BLAKE2b-256 | 509056d8747a232dd9290e9d734d520ca232085aa3c9e699fe04247c5a36ca47 |