Polyfactory

3.3.0 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This example demonstrates how to use `ModelFactory` to generate mock Pydantic model instances. `ModelFactory.build()` creates a single instance in memory, while `ModelFactory.batch()` creates a list of instances. For persistence, a `PersistenceStrategy` would be required with `ModelFactory.create()`.

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)}")

view raw JSON →