Skip to main content

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

Project description

Registerer

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

Installation

pip install registerer

Examples

Register a Function With Validator

import registerer

database_registry = registerer.Registerer(
    validators=[registerer.RegistryValidator(lambda item: not getattr(item, "fail", False))]
)

# success:
@database_registry.register("sqlite")
def sqlite_database_connection(name: str):
    return f"sqlite connection {name}"


# failure:
# registerer.exceptions.RegistrationError: custom validation failed when registering postgres_database_connection
@database_registry.register("postgres", fail=True)
def postgres_database_connection(name: str):
    return f"postgres connection {name}"


def main():
    print(database_registry["postgres"]("personal"))  # postgres connection personal


if __name__ == "__main__":
    main()

Register a Function

# Register functions:

from registerer import Registerer

database_registry = Registerer()


@database_registry.register
def sqlite():
    return "sqlite connection"


@database_registry.register("postgres")
def postgres_backup():
    return "postgres connection"


def main():
    print(database_registry["sqlite"]())  # sqlite connection
    print(database_registry["postgres"]())  # postgres connection


if __name__ == "__main__":
    main()

Register a Class With Custom Validator

import registerer


class Animal:
    is_wild: bool = None


domestic_animals_registry = registerer.Registerer(
    Animal,
    max_size=4,
    validators=[
        registerer.RegistryValidator(
            lambda item: not item.is_wild,
            error="only domestic animals allowed.",  # Optional
        ),
    ],
)


# success:
@domestic_animals_registry.register("cow")
class Cow(Animal):
    is_wild = False


# failure:
# raises registerer.exceptions.RegistrationError: Lion is wild, only domestic animals are allowed to register.
@domestic_animals_registry.register("lion")
class Lion(Animal):
    is_wild = True

Register a Class

# Register classes with the same interface,
# enforce the type check and enjoy the benefits of type hints:


from registerer import Registerer


class Animal:
    def talk(self) -> None:
        raise NotImplementedError


# create a registry that requires registered items to implement the Animal interface:
animal_registry = Registerer(Animal)


@animal_registry.register("dog")
class Dog(Animal):
    def talk(self) -> None:
        return "woof"


def main():
    print(animal_registry["dog"])  # <class '__main__.Dog'>
    print(animal_registry["dog"]())  # <__main__.Dog object at 0x7f108ad37d60>
    print(animal_registry["dog"]().talk())  # woof


if __name__ == "__main__":
    main()

Reference

module registerer.registry


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[Type[~Type]] = None,
    max_size: int = None,
    validators: Optional[List] = None
)

Args:

  • parent_item: The class of parent. Defaults to None.
  • max_size: allowed size of registered items. Defaults to None.
  • validators: validate each item on register. Defaults to None.

property Registerer.items

get actual registered items (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: ~Type)

validate the item during registration.

Args:

  • item (Type): item want to register.

Raises:

  • RegistrationError: can't register this item.

module registerer.validators


class RegistryValidator

a utility for custom validation with the Registerer. you can subclass this and override the on_register method, and raise an exception if you must.

examples:

### <kbd>method</kbd> `RegistryValidator.__init__`

```python
__init__(validator, error: str = None)  None

module registerer.exceptions


class RegistrationError

Errors that occurs on registering new item.


class ItemAlreadyRegistered

You've registered a item with duplicate identifier.


class ItemNotRegistered

You've tried to get a item that is not registered.

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.3.0.tar.gz (6.6 kB view details)

Uploaded Source

Built Distribution

registerer-0.3.0-py3-none-any.whl (6.5 kB view details)

Uploaded Python 3

File details

Details for the file registerer-0.3.0.tar.gz.

File metadata

  • Download URL: registerer-0.3.0.tar.gz
  • Upload date:
  • Size: 6.6 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

Hashes for registerer-0.3.0.tar.gz
Algorithm Hash digest
SHA256 ced3aa82f3fc159b32f0d7df2ffdc4483a0a88d57ed6ef52b8cb4ba1cbde18c4
MD5 3de355e3239d81c270c4ad77dfc79178
BLAKE2b-256 297d5315b947b4217b1b646827536d9b5a9bd6b8e43b77e4e925164193bf209d

See more details on using hashes here.

File details

Details for the file registerer-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: registerer-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 6.5 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

Hashes for registerer-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 0b3c57895eb912401f2ac9813f7c5df020cdf58a5f5e7189b282a04deff9ef00
MD5 fa6288682516a42e43051edbfd8157c1
BLAKE2b-256 9521414c3600268b98250f1ed260ed6aab3b9a95a59eebf73730ce8e8d0c6c8a

See more details on using hashes here.

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