python-registrable

CircleCI License PyPI version Documentation Status

Python module that provides a Registrable base class. Based on the implementation from AllenNLP.

This is useful in scenarios where each particular subclass implementation of some base class has a natural association with a unique string, or where you’d prefer to create such an association, like when you need to specify which subclasses to use in a human-readable configuration file.

Installing

The quickest way to install is through PyPI.

pip install registrable

Usage

The basic way to use registrable is to create a Registrable base class and then “register” subclass implementations under sensible names:

>>> from registrable import Registrable
>>> class MyBaseClass(Registrable):
...    def do_something(self):
...        raise NotImplementedError

To register subclass implementations of your base class:

>>> @MyBaseClass.register("first_implementation")
... class SubclassA(MyBaseClass):
...     def do_something(self):
...         return 1

Then access an implementation by calling .by_name() on the base class:

>>> subclass = MyBaseClass.by_name("first_implementation")
>>> instance = subclass()
>>> instance.do_something()
1

You can easily check if a given name is registered:

>>> MyBaseClass.is_registered("first_implementation")
True
>>> MyBaseClass.is_registered("anything else?")
False

And you can list all registered names or iterate through tuples of registered names and their corresponding subclasses:

>>> MyBaseClass.list_available()
['first_implementation']
>>> list(MyBaseClass.iter_registered())
[('first_implementation', <class '__main__.SubclassA'>)]