samedi 9 octobre 2021

Creating instances of user-defined class in the setting of Python package

A Python package defines a base class, which the user is supposed to derive child classes from. Also, the package needs to create those instances without prior knowledge of the possible subclasses. Can I achieve this by __init_subclass__?

Specifically, I'm hoping to do something like this:

class BaseClass(ABC):
    _registry = {}
    _class_signature = None

    @classmethod
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        if cls._class_signature is None:
            raise KeyError('Missing signature')
        elif cls._class_signature in cls._registry :
            raise KeyError('Conflict in signature')
        else:
            cls._registry[cls._class_signature] = cls

    @classmethod
    def get_class_registry(cls):
        return cls._registry

    def __init__(self, params):
        pass

where all classes are recorded in _registry. The user of the package will create subclasses deriving from this (the subclass must have its own signature or else it throws). Meanwhile in another module of the package, I would like to have the ability to create instances of any derived classes using the signatures together with the register dictionary, without the need for if...else structures, something like (assuming 'sig1' is the unique signature of some derived class)

new_instance = BaseClass(SignalBase._registry()['sig1'])

Can this be done?





Aucun commentaire:

Enregistrer un commentaire