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.
pip install polyfactoryVerified import paths — ran on the pinned version, not inferred.
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()`.
Update imports from `from polyfactory.factories.base import Factory` to `from polyfactory.factories import PolyFactory`.
When using `create()`, you must now pass a persistence strategy (e.g., `SyncPersistenceStrategy`) as an argument. The `use_api_client` parameter was also removed in v3.0.0.
`build()` generates an in-memory instance without any persistence, useful for simple object creation. `create()` is designed to persist the generated data and requires a `PersistenceStrategy` to do so (e.g., saving to a database or calling an API).
For generic factories, the `__model__` attribute should be defined as a class variable within the `PolyFactory` subclass itself, rather than being passed as an argument to `build()` or `create()` methods (which is now deprecated for this purpose).
For Pydantic models, use `ModelFactory`. For Dataclasses, use `DataclassFactory`. These specific factories offer tailored functionality and better integration than configuring `PolyFactory` with `__model__`.