design_pytterns.factory package

Factory class

class design_pytterns.factory.factory.Factory(registered_classes: Optional[MutableMapping[Hashable, Type[Any]]] = None)

Bases: object

Generic Factory-pattern based on hashable id class registration.

Parameters

registered_classes (dict, optional) – A dictionary that maps the hashable identifiers with their class types.

create(class_id: Hashable, *args: Any, **kwargs: Any)Any

Create a class instance given its identifier and constructor arguments.

Changed in version 0.2.0: raises UnregisteredClassIdError instead of TypeError.

Parameters
  • class_id (Hashable) – The class identifer.

  • *args (Any) – Variable length arguments of the class constructor associated to the value of class_id.

  • **kwargs (Any) – Keyword arguments of class constructor associated to the value of class_id.

Returns

Initialized class instance associated to the value of class_id.

Return type

Any

Raises

UnregisteredClassIdError – If class_id is unknown.

register_class(class_id: Hashable, class_type: Type[Any])None

Register a class by a hashable identifier.

Parameters
  • class_id (Hashable) – The class identifer.

  • class_type (type) – The class type.

Warning

Overwrite any previously mapped type if its class id is already in use and log a warning about the replacement.

SubclassFactory class

class design_pytterns.factory.subclass_factory.SubclassFactory(base_class: Type[design_pytterns.interfaces.subclass_identifiable.SubclassIdentifiable])

Bases: design_pytterns.factory.factory.Factory

Automatic concrete sublass registration factory.

Factory that analyzes the subclass hierarchy of the given base class that inherits from SubclassIdentifiable and registers all of the concrete subclasses with their associated class id automatically.

Parameters

base_class (SubclassIdentifiable) – The base class that servers as the starting point of the subclass hierarchy analysis.