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_item=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_item: Optional[~T] = None,
max_size: Optional[int] = None,
validators: Optional[List[registerer.validators.RegistryValidator]] = None
)
Args:
parent_item
: 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.3.1.tar.gz
.
File metadata
- Download URL: registerer-0.3.1.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.7-arch1-1
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 1e4dcc8c23f0006974151dc81e63d8692bcc2720740b5e975a663b674af6729e |
|
MD5 | 14dd54cb3b350be3286cbf8a050a5591 |
|
BLAKE2b-256 | 4bbd85f0d6614c8f14ab3efd62b7f47ef0fcd897c2e2c463f4f1d74171a6da4c |
File details
Details for the file registerer-0.3.1-py3-none-any.whl
.
File metadata
- Download URL: registerer-0.3.1-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.7-arch1-1
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | ba0d10eafdfb4f73e67d30f4870fd625b3fcf689f3de4ad9699cb77c71562fc9 |
|
MD5 | e0d5a6e885532861f1b8cb6380e91e6a |
|
BLAKE2b-256 | 0d6aa746212b83eff5f966ba0d07edb3585c8656f68b8cc951eb97b916ffb793 |