Skip to main content

Everything you need to implement maintainable and easy to use registry patterns in your project.

Project description

Registerer

pypi ci codecov license

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(item_or_custom_slug: Union[~T, str] = None, **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


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

registerer-0.4.2.tar.gz (7.9 kB view hashes)

Uploaded Source

Built Distribution

registerer-0.4.2-py3-none-any.whl (7.2 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page