base_factory#

class polyfactory.factories.base.BuildContext#

Bases: TypedDict

class polyfactory.factories.base.BaseFactory#

Bases: ABC, Generic[T]

Base Factory class - this class holds the main logic of the library

__model__: type[T]#

The model for the factory. This attribute is required for non-base factories and an exception will be raised if it’s not set. Can be automatically inferred from the factory generic argument.

__check_model__: bool = False#

Flag dictating whether to check if fields defined on the factory exists on the model or not. If ‘True’, checks will be done against Use, PostGenerated, Ignore, Require constructs fields only.

__allow_none_optionals__: ClassVar[bool] = True#

Flag dictating whether to allow ‘None’ for optional values. If ‘True’, ‘None’ will be randomly generated as a value for optional model fields

__sync_persistence__: type[SyncPersistenceProtocol[T]] | SyncPersistenceProtocol[T] | None = None#

A sync persistence handler. Can be a class or a class instance.

__async_persistence__: type[AsyncPersistenceProtocol[T]] | AsyncPersistenceProtocol[T] | None = None#

An async persistence handler. Can be a class or a class instance.

__set_as_default_factory_for_type__ = False#

Flag dictating whether to set as the default factory for the given type. If ‘True’ the factory will be used instead of dynamically generating a factory for the type.

__is_base_factory__: bool = False#

Flag dictating whether the factory is a ‘base’ factory. Base factories are registered globally as handlers for types. For example, the ‘DataclassFactory’, ‘TypedDictFactory’ and ‘ModelFactory’ are all base factories.

__base_factory_overrides__: dict[Any, type[BaseFactory[Any]]] | None = None#

A base factory to override with this factory. If this value is set, the given factory will replace the given base factory.

Note: this value can only be set when ‘__is_base_factory__’ is ‘True’.

__faker__: ClassVar['Faker'] = <faker.proxy.Faker object>#

A faker instance to use. Can be a user provided value.

__random__: ClassVar['Random'] = <random.Random object>#

An instance of ‘random.Random’ to use.

__random_seed__: ClassVar[int]#

An integer to seed the factory’s Faker and Random instances with. This attribute can be used to control random generation.

__randomize_collection_length__: ClassVar[bool] = False#

Flag dictating whether to randomize collections lengths.

__min_collection_length__: ClassVar[int] = 0#

An integer value that defines minimum length of a collection.

__max_collection_length__: ClassVar[int] = 5#

An integer value that defines maximum length of a collection.

__use_defaults__: ClassVar[bool] = False#

Flag indicating whether to use the default value on a specific field, if provided.

__config_keys__: tuple[str, ...] = ('__check_model__', '__allow_none_optionals__', '__set_as_default_factory_for_type__', '__faker__', '__random__', '__randomize_collection_length__', '__min_collection_length__', '__max_collection_length__', '__use_defaults__')#

Keys to be considered as config values to pass on to dynamically created factories.

classmethod is_factory_type(annotation: Any) bool#

Determine whether a given field is annotated with a type that is supported by a base factory.

Parameters:

annotation – A type annotation.

Returns:

Boolean dictating whether the annotation is a factory type

classmethod is_batch_factory_type(annotation: Any) bool#

Determine whether a given field is annotated with a sequence of supported factory types.

Parameters:

annotation – A type annotation.

Returns:

Boolean dictating whether the annotation is a batch factory type

classmethod extract_field_build_parameters(field_meta: FieldMeta, build_args: dict[str, Any]) Any#

Extract from the build kwargs any build parameters passed for a given field meta - if it is a factory type.

Parameters:
  • field_meta – A field meta instance.

  • build_args – Any kwargs passed to the factory.

Returns:

Any values

abstract classmethod is_supported_type(value: Any) TypeGuard[type[T]]#

Determine whether the given value is supported by the factory.

Parameters:

value – An arbitrary value.

Returns:

A typeguard

classmethod seed_random(seed: int) None#

Seed faker and random with the given integer.

Parameters:

seed – An integer to set as seed.

Returns:

‘None’

classmethod is_ignored_type(value: Any) bool#

Check whether a given value is an ignored type.

Parameters:

value – An arbitrary value.

Notes:
  • This method is meant to be overwritten by extension factories and other subclasses

Returns:

A boolean determining whether the value should be ignored.

classmethod get_provider_map() dict[Any, Callable[[], Any]]#

Map types to callables.

Notes:
  • This method is distinct to allow overriding.

Returns:

a dictionary mapping types to callables.

classmethod create_factory(model: type[T] | None = None, bases: tuple[type[polyfactory.factories.base.BaseFactory[Any]], ...] | None = None, **kwargs: Any) type[F]#

Generate a factory for the given type dynamically.

Parameters:
  • model – A type to model. Defaults to current factory __model__ if any. Otherwise, raise an error

  • bases – Base classes to use when generating the new class.

  • kwargs – Any kwargs.

Returns:

A ‘ModelFactory’ subclass.

classmethod get_field_value(field_meta: FieldMeta, field_build_parameters: Any | None = None, build_context: BuildContext | None = None) Any#

Return a field value on the subclass if existing, otherwise returns a mock value.

Parameters:
  • field_meta – FieldMeta instance.

  • field_build_parameters – Any build parameters passed to the factory as kwarg values.

  • build_context – BuildContext data for current build.

Returns:

An arbitrary value.

classmethod get_field_value_coverage(field_meta: FieldMeta, field_build_parameters: Any | None = None, build_context: BuildContext | None = None) Iterable[Any]#

Return a field value on the subclass if existing, otherwise returns a mock value.

Parameters:
  • field_meta – FieldMeta instance.

  • field_build_parameters – Any build parameters passed to the factory as kwarg values.

  • build_context – BuildContext data for current build.

Returns:

An iterable of values.

classmethod should_set_none_value(field_meta: FieldMeta) bool#

Determine whether a given model field_meta should be set to None.

Parameters:

field_meta – Field metadata.

Notes:
  • This method is distinct to allow overriding.

Returns:

A boolean determining whether ‘None’ should be set for the given field_meta.

classmethod should_use_default_value(field_meta: FieldMeta) bool#

Determine whether to use the default value for the given field.

Parameters:

field_meta – FieldMeta instance.

Notes:
  • This method is distinct to allow overriding.

Returns:

A boolean determining whether the default value should be used for the given field_meta.

classmethod should_set_field_value(field_meta: FieldMeta, **kwargs: Any) bool#

Determine whether to set a value for a given field_name.

Parameters:
  • field_meta – FieldMeta instance.

  • kwargs – Any kwargs passed to the factory.

Notes:
  • This method is distinct to allow overriding.

Returns:

A boolean determining whether a value should be set for the given field_meta.

abstract classmethod get_model_fields() list[FieldMeta]#

Retrieve a list of fields from the factory’s model.

Returns:

A list of field MetaData instances.

classmethod get_factory_fields() list[tuple[str, Any]]#

Retrieve a list of fields from the factory.

Trying to be smart about what should be considered a field on the model, ignoring dunder methods and some parent class attributes.

Returns:

A list of tuples made of field name and field definition

classmethod process_kwargs(**kwargs: Any) dict[str, Any]#

Process the given kwargs and generate values for the factory’s model.

Parameters:

kwargs – Any build kwargs.

Returns:

A dictionary of build results.

classmethod process_kwargs_coverage(**kwargs: Any) Iterable[dict[str, Any]]#

Process the given kwargs and generate values for the factory’s model.

Parameters:
  • kwargs – Any build kwargs.

  • build_context – BuildContext data for current build.

Returns:

A dictionary of build results.

classmethod build(**kwargs: Any) T#

Build an instance of the factory’s __model__

Parameters:

kwargs – Any kwargs. If field names are set in kwargs, their values will be used.

Returns:

An instance of type T.

classmethod batch(size: int, **kwargs: Any) list[T]#

Build a batch of size n of the factory’s Meta.model.

Parameters:
  • size – Size of the batch.

  • kwargs – Any kwargs. If field_meta names are set in kwargs, their values will be used.

Returns:

A list of instances of type T.

classmethod coverage(**kwargs: Any) Iterator[T]#

Build a batch of the factory’s Meta.model will full coverage of the sub-types of the model.

Parameters:

kwargs – Any kwargs. If field_meta names are set in kwargs, their values will be used.

Returns:

A iterator of instances of type T.

classmethod create_sync(**kwargs: Any) T#

Build and persists synchronously a single model instance.

Parameters:

kwargs – Any kwargs. If field_meta names are set in kwargs, their values will be used.

Returns:

An instance of type T.

classmethod create_batch_sync(size: int, **kwargs: Any) list[T]#

Build and persists synchronously a batch of n size model instances.

Parameters:
  • size – Size of the batch.

  • kwargs – Any kwargs. If field_meta names are set in kwargs, their values will be used.

Returns:

A list of instances of type T.

async classmethod create_async(**kwargs: Any) T#

Build and persists asynchronously a single model instance.

Parameters:

kwargs – Any kwargs. If field_meta names are set in kwargs, their values will be used.

Returns:

An instance of type T.

async classmethod create_batch_async(size: int, **kwargs: Any) list[T]#

Build and persists asynchronously a batch of n size model instances.

Parameters:
  • size – Size of the batch.

  • kwargs – Any kwargs. If field_meta names are set in kwargs, their values will be used.

Returns:

A list of instances of type T.