bagof.factories.base
Base class for all factories.
Attributes
FactoryRegistry
module-attribute
A registry of factories, mapping type hints to factory classes.
register_factory
module-attribute
Backward-compatible alias for Factory.register
get_factory_class
module-attribute
Backward-compatible alias for Factory.get_class
Classes
Factory
Base class for magic factories.
Factories build a default value for a type hint. They are registered in
a global registry and looked up by type hint. The base factory builds a
value by instantiating the hint's fallback
concrete type.
A factory class can register itself for one or more type hints directly in
its class definition with the register keyword:
Methods:
register
staticmethod
register(factory: Type[Factory], *hints: Unpack[tuple[Any]], registry: FactoryRegistry = ...) -> Type[Factory]
register(*hints: Unpack[tuple[Any]], registry: FactoryRegistry = ...) -> ClassDecorator
Register a factory class for one or more type hints.
Can be used as a decorator or called directly:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*hints
|
Any
|
One or more type hints to register the factory class for.
Defaults to the class's |
()
|
registry
|
FactoryRegistry
|
The registry to register the factory class in. Defaults to the global registry. |
FACTORIES
|
get
staticmethod
get(hint: Any, registry: FactoryRegistry = FACTORIES, fallback: Type[Factory] | None = UNSET) -> Factory | None
Get the best-matching factory for a given type hint.
Example
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hint
|
Any
|
The type hint for which to get a factory. |
required |
registry
|
FactoryRegistry
|
The registry to look up the factory in. Defaults to the global registry. |
FACTORIES
|
fallback
|
Optional[Type[Factory]]
|
The fallback factory class to use if no matching factory is found.
Defaults to |
UNSET
|
Returns:
| Type | Description |
|---|---|
Optional[Factory]
|
The best-matching factory for the given type hint, or |
get_class
staticmethod
get_class(hint: Any, registry: FactoryRegistry = FACTORIES, fallback: Type[Factory] | None = UNSET) -> Type[Factory] | None
Get the best-matching factory class for a given type hint.
Warning
By default an unmatched hint returns the base
Factory class, never None. Pass fallback=None
explicitly to get None back instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hint
|
Any
|
The type hint for which to get a factory class. |
required |
registry
|
FactoryRegistry
|
The registry to look up the factory class in. Defaults to the global registry. |
FACTORIES
|
fallback
|
Optional[Type[Factory]]
|
The fallback factory class to use if no matching factory is found.
Defaults to |
UNSET
|
Returns:
| Type | Description |
|---|---|
Optional[Type[Factory]]
|
The best-matching factory class for the given type hint, or |