Everything you need to implement maintainable and easy to use registry patterns in your project.
Project description
Registerer
Implement maintainable and easy to use registry patterns in your project.
TLDR; Write this:
import registerer
command_handler_registry = registerer.Registerer()
@command_handler_registry.register
def hello(args):
return "hello to you too"
@command_handler_registry.register
def info(args):
return "how can i help you?"
@command_handler_registry.register
def play(args):
return "let me play a song for you"
command = "info"
args = {}
assert command_handler_registry[command](args) == "how can i help you?"
Instead of this, which violates the Open-Closed Principle (OCP):
def hello(args):
return "hello to you too"
def info(args):
return "how can i help you?"
def play(args):
return "let me play a song for you"
def command_handler(command, args):
if command == "hello":
return hello(args)
if command == "info":
return info(args)
if command == "play":
return play(args)
command = "info"
args = {}
assert command_handler(command, args) == "how can i help you?"
Installation
pip install registerer
Usage
In order to use registerer, you need to instantiate from the registerer.Registerer
.
There is several optional arguments you can pass to the Registerer
constructor
to manage how registry object should behave (Read more in reference section).
let's create a registry:
import abc
class Animal(abc.ABC):
is_wild: bool = None
@abc.abstractmethod
def walk(self):
pass
# Animal class registry
animal_registry = registerer.Registerer(
parent_class=Animal,
max_size=5, # only 5 items can register
validators=[
registerer.RegistryValidator(
lambda item: item.is_wild is False, # check passed if returns True
error="can't register wild animal.",
),
],
)
Now with animal_registry
you can register your classes:
# use the name of class as unique identifier:
@animal_registry.register
class Sheep(Animal):
is_wild = False
def walk(self):
return "sheep walks"
# use your custom slug as unique identifier:
@animal_registry.register("kitty")
class Cat(Animal):
is_wild = False
def walk(self):
return "cat walks"
assert animal_registry["Sheep"] == Sheep
assert animal_registry["kitty"] == Cat
assert animal_registry.items == [Sheep, Cat]
assert animal_registry._registry_dict == {"sheep": Sheep, "kitty": Cat}
assert animal_registry["Sheep"]().walk() == "sheep walks"
assert animal_registry["kitty"]().walk() == "cat walks"
The register
method will also set an attribute on the registered item as registry_slug
.
So, in last example we have:
assert Cat.registry_slug == "kitty"
assert animal_registry["kitty"].registry_slug == "kitty"
if you need to add attributes on the registered item on registration (it's optional), you can pass kwargs to the register
method.
This is useful when registering functions. for example:
# function registry
test_database_registry = registerer.Registerer(
validators=[
registerer.RegistryValidator(
lambda item: item.db_type == "test",
),
]
)
# use the name of function as unique identifier:
@test_database_registry.register(db_type="test")
def sqlite(name: str):
return f"sqlite connection {name}"
# use your custom slug as unique identifier:
@test_database_registry.register("postgresql", db_type="test")
def postgresql_test(name: str):
return f"postgresql connection {name}"
assert test_database_registry["sqlite"]("quera") == f"sqlite connection quera"
assert test_database_registry["postgresql"]("quera") == f"postgresql connection quera"
Exceptions
module registerer.exceptions
class RegistryCreationError
Errors that occurs on creating a registry object.
class RegistrationError
Errors that occurs on registering new item.
class ItemNotRegistered
You've tried to get a item that is not registered.
Reference
Here is all the things you can do with the Registerer
class:
class Registerer
A utility that can be used to create a registry object to register class or functions.
method Registerer.__init__
__init__(
parent_class: Optional[~T] = None,
max_size: Optional[int] = None,
validators: Optional[List[registerer.validators.RegistryValidator]] = None
)
Args:
parent_class
: The class of parent. If you set this, the registered class should be subclass of the this, If it's not the register method going to raise RegistrationError. Also by setting this you'll be benefit from type hints in your IDE.max_size
: allowed size of registered items. Defaults to None which means there is no limit.validators
: custom validation for on registering items.
Raises:
RegistryCreationError
: Can't create proper registry object.
property Registerer.items
get actual registered items as list (classes or functions)
method Registerer.is_registered
is_registered(slug: str) → bool
is the slug registered?
method Registerer.register
register(*args, **kwargs)
register a class or item to the registry
example:
# register the item with it's name
@registry.register
class Foo:
pass
assert registry["Foo"] == Foo
# register the item with a custom name
@registry.register("bar")
class Bar:
pass
assert registry["bar"] == Bar
# register the item with a custom name and also add some other attributes to it.
# it is more useful when registering functions.
@db_registry.register("postgresql", env="prod")
def postgresql_connection:
pass
assert registry["postgresql"] == postgresql_connection
assert postgresql_connection.env == "prod"
method Registerer.validate
validate(item: ~T)
validate the item during registration.
Args:
item
(T): item want to register.
Raises:
RegistrationError
: can't register this item.
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
File details
Details for the file registerer-0.4.0.tar.gz
.
File metadata
- Download URL: registerer-0.4.0.tar.gz
- Upload date:
- Size: 7.9 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.1.15 CPython/3.10.7 Linux/5.19.8-arch1-1
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 99e66664315c6fd363765d7b587d4ed3710880f815a42cdda43d80c8ddb60d90 |
|
MD5 | 5cc07e93851b284729444f3af308c898 |
|
BLAKE2b-256 | 5f060d320a363150f4fa1cdc448c82893589d5e6a22891de13a7283aa109b3cc |
File details
Details for the file registerer-0.4.0-py3-none-any.whl
.
File metadata
- Download URL: registerer-0.4.0-py3-none-any.whl
- Upload date:
- Size: 7.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/1.1.15 CPython/3.10.7 Linux/5.19.8-arch1-1
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 5444f545ac5d802b62aadeffcd160da4c1f7d20a92f2ec18fb8af6f65e04a83f |
|
MD5 | 23dcd2879a25bb013b9379a39e3c6711 |
|
BLAKE2b-256 | 05725dbaede634989b4119c1ccbaeb123ee856811c16ca9bfcf509588d75dc8f |