or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

customization.mdfactory-operations.mdfield-configuration.mdindex.mdpersistence.mdspecialized-factories.md
tile.json

tessl/pypi-polyfactory

Mock data generation factories for Python types with support for dataclasses, Pydantic, SQLAlchemy, and more

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/polyfactory@2.22.x

To install, run

npx @tessl/cli install tessl/pypi-polyfactory@2.22.0

index.mddocs/

Polyfactory

Polyfactory is a comprehensive mock data generation library for Python that automatically creates realistic test data based on type hints. It supports multiple data modeling libraries including dataclasses, TypedDict, Pydantic models, msgspec structs, SQLAlchemy models, and more, enabling developers to generate complex, interrelated data structures with minimal configuration.

Package Information

  • Package Name: polyfactory
  • Language: Python
  • Installation: pip install polyfactory
  • Optional Dependencies:
    • pip install polyfactory[pydantic] - Pydantic model support
    • pip install polyfactory[sqlalchemy] - SQLAlchemy model support
    • pip install polyfactory[full] - All optional dependencies

Core Imports

from polyfactory import BaseFactory
from polyfactory.factories import DataclassFactory, TypedDictFactory

For specific factory types:

from polyfactory.factories.pydantic_factory import ModelFactory
from polyfactory.factories.sqlalchemy_factory import SQLAlchemyFactory

Field configuration:

from polyfactory import Use, Ignore, Require, PostGenerated

Basic Usage

from dataclasses import dataclass
from polyfactory.factories import DataclassFactory

@dataclass
class Person:
    name: str
    age: int
    email: str

class PersonFactory(DataclassFactory[Person]):
    __model__ = Person

# Generate single instance
person = PersonFactory.build()
print(person.name)  # Generated name like "John Doe"
print(person.age)   # Generated age like 25
print(person.email) # Generated email like "user@example.com"

# Generate multiple instances
people = PersonFactory.batch(5)

# Customize specific fields
person = PersonFactory.build(name="Alice", age=30)

Architecture

Polyfactory is built around a hierarchical factory system:

  • BaseFactory: Core factory class providing build, batch, and persistence methods
  • Specialized Factories: Type-specific factories (DataclassFactory, ModelFactory, etc.)
  • Field Configuration: Special field types (Use, Ignore, Require, PostGenerated) for customizing generation
  • Persistence Protocols: Integration with databases and storage systems
  • Value Generators: Constraint-aware generators for specialized types
  • Provider System: Extensible type-to-value mapping for custom types

This architecture enables polyfactory to handle complex data generation scenarios while maintaining type safety and providing extensive customization options for any Python object model.

Capabilities

Core Factory Operations

Essential factory methods for building instances, batches, and managing the generation lifecycle. These methods form the foundation of all polyfactory usage patterns.

class BaseFactory:
    @classmethod
    def build(cls, **kwargs) -> T: ...
    @classmethod
    def batch(cls, size: int, **kwargs) -> list[T]: ...
    @classmethod
    def coverage(cls, **kwargs) -> Iterator[T]: ...

Factory Operations

Specialized Factory Classes

Type-specific factory implementations for different Python object modeling libraries, each optimized for their respective type systems and features.

class DataclassFactory(BaseFactory[T]): ...
class TypedDictFactory(BaseFactory[TypedDictT]): ...
class ModelFactory(BaseFactory[T]): ...  # Pydantic
class SQLAlchemyFactory(BaseFactory[T]): ...

Specialized Factories

Field Configuration

Special field types and decorators that control how individual attributes are generated, providing fine-grained control over the data generation process.

class Use: ...
class Ignore: ...
class Require: ...
class PostGenerated: ...

Field Configuration

Persistence Integration

Protocols and handlers for persisting generated data to databases and storage systems, supporting both synchronous and asynchronous operations.

class SyncPersistenceProtocol: ...
class AsyncPersistenceProtocol: ...

Persistence

Provider System and Customization

Extensible system for registering custom value generators and configuring the factory behavior for specific types and use cases.

@classmethod
def add_provider(cls, type_: type, provider: Callable): ...
@classmethod
def seed_random(cls, seed: int): ...

Customization

Types

# Configuration attributes for factory classes
__model__: type  # The model type for the factory
__faker__: Faker  # Faker instance for data generation
__random__: Random  # Random instance for randomization
__sync_persistence__: SyncPersistenceProtocol | None
__async_persistence__: AsyncPersistenceProtocol | None
__randomize_collection_length__: bool
__min_collection_length__: int
__max_collection_length__: int
__allow_none_optionals__: bool
__use_defaults__: bool
__check_model__: bool

# Exception types
class ConfigurationException(Exception): ...
class ParameterException(Exception): ...
class MissingBuildKwargException(Exception): ...