Polyfactory
Polyfactory is a versatile Python library for generating mock data, primarily used for testing and development. It supports various data models, including Pydantic, SQLAlchemy, and Dataclasses, offering a flexible API for customization. The current version is 3.3.0, and it maintains an active release cadence with regular updates and feature enhancements.
Warnings
- breaking The generic `Factory` class was renamed to `PolyFactory`.
- breaking The `create()` method now explicitly requires a persistence strategy.
- gotcha Confusion between `build()` and `create()` methods.
- gotcha Defining the target model for generic `PolyFactory` instances.
- gotcha Using the generic `PolyFactory` when a specific factory type is available.
Install
-
pip install polyfactory -
pip install 'polyfactory[pydantic]'
Imports
- ModelFactory
from polyfactory.factories import ModelFactory
- PolyFactory
from polyfactory.factories import PolyFactory
- SyncPersistenceStrategy
from polyfactory.persistence import SyncPersistenceStrategy
- AsyncPersistenceStrategy
from polyfactory.persistence import AsyncPersistenceStrategy
Quickstart
from polyfactory.factories import ModelFactory
from pydantic import BaseModel
from datetime import date
class User(BaseModel):
name: str
email: str
age: int
is_active: bool = True
joined_date: date
# Build a single instance (in-memory, no persistence)
user_instance = ModelFactory.build(User)
print(f"Generated User: {user_instance.model_dump_json(indent=2)}")
# Build multiple instances (in-memory list)
users_batch = ModelFactory.batch(User, size=3)
print(f"\nGenerated Users Batch (first item): {users_batch[0].model_dump_json(indent=2)}")