Skip to content

ConstructionFactory

ConstructionFactory

Bases: Generic[T]

Base class for a factory whose objects are created from a registered constructor.

related

Attributes

constructors instance-attribute

constructors = constructors or {}

Functions

__getitem__

__getitem__(key: str) -> type[T]

Return the type by the key.

Returns:

Type Description
type[T]

type by the key.

Raises:

Type Description
KeyError

when the key is not in the constructors

__init__

__init__(constructors: dict[str, type[T]] | None = None) -> None

Constructor.

Parameters:

Name Type Description Default
constructors dict[str, type[T]] | None

dictionary of constructors

None

__iter__

__iter__() -> Iterator[str]

Return the iterator of the factory.

Returns:

Type Description
Iterator[str]

iterator of the factory.

__len__

__len__() -> int

Return the number of constructors in the factory.

Returns:

Type Description
int

number of constructors in the factory.

__repr__

__repr__() -> str

Return the Python code to construct the factory.

Returns:

Type Description
str

Python code to construct the factory.

__setitem__

__setitem__(key: str, value: type[T]) -> None

Set the value for the key.

Parameters:

Name Type Description Default
key str

name of the constructor

required
value type[T]

type of the constructor

required

__str__

__str__() -> str

Return the class name of the factory.

Returns:

Type Description
str

class name of the factory.

construct

construct(key: str, **kwargs: Any) -> T

Create an object from the constructor registered by the key.

Parameters:

Name Type Description Default
key str

name of the constructor

required
**kwargs Any

parameters to pass to the constructor

{}

Returns:

Type Description
T

object created from the constructor registered by the key

Raises:

Type Description
ValueError

when the key is not registered

import_from

import_from(module: ModuleType, cls: type[T]) -> list[type[T]]

Import constructors from the module.

Parameters:

Name Type Description Default
module ModuleType

module to import constructors

required
cls type[T]

class of constructors to import

required

Returns:

Type Description
list[type[T]]

list of constructors imported from the module.