Skip to content
Development
Skill

/polyfactory

Use when working with polyfactory, ModelFactory, DataclassFactory, MsgspecFactory, AttrsFactory, Use, register_fixture, pytest plugin, __random_seed__, or coverage(). Not for production seeding.

From plugin
litestar
1720 skills1 agent2 hooks

Claude Code

$ npx -y skills add litestar-org/litestar-skills --skill polyfactory --agent claude-code

SKILL.md

polyfactory.SKILL.md
name: polyfactory
description: "Use when working with polyfactory, ModelFactory, DataclassFactory, MsgspecFactory, AttrsFactory, Use, register_fixture, pytest plugin, __random_seed__, or coverage(). Not for production seeding."

polyfactory

Polyfactory is a typed mock-data factory library: declare `ModelFactory[T]` (or `DataclassFactory`, `MsgspecFactory`, `AttrsFactory`, `TypedDictFactory`) and `.build()` returns a populated instance of `T`. The matching factory base inspects the model's annotations and supported constraints so tests do not need hand-written happy-path fixtures.

In Litestar projects, polyfactory's pytest plugin is the canonical way to feed `TestClient.post(...)` / `AsyncTestClient.put(...)` payloads. The companion skill `litestar:litestar-testing` covers the request side.

Code Style Rules

  • PEP 604 unions: `T | None`, never `Optional[T]`.
  • One factory per model. Don't reuse a factory across unrelated models — clarity beats DRY when the test fails at 3am.
  • Pick the right factory base by backend: `ModelFactory` (Pydantic), `DataclassFactory`, `MsgspecFactory`, `AttrsFactory`, `TypedDictFactory`. A mismatched base raises `ConfigurationException`.
  • Prefer `register_fixture` over hand-rolled `@pytest.fixture` wrappers. Call it in a pytest-discovered test module or `conftest.py` so the injected fixture is collected.

Quick Reference

Picking the right factory base

| Model kind | Factory base | Import | | --- | --- | --- | | `pydantic.BaseModel` | `ModelFactory` | `from polyfactory.factories.pydantic_factory import ModelFactory` | | `@dataclass` | `DataclassFactory` | `from polyfactory.factories.dataclass_factory import DataclassFactory` | | `msgspec.Struct` | `MsgspecFactory` | `from polyfactory.factories.msgspec_factory import MsgspecFactory` | | `@attrs.define` / `attr.s` | `AttrsFactory` | `from polyfactory.factories.attrs_factory import AttrsFactory` | | `TypedDict` | `TypedDictFactory` | `from polyfactory.factories.typed_dict_factory import TypedDictFactory` | | SQLAlchemy declarative | `SQLAlchemyFactory` | `from polyfactory.factories.sqlalchemy_factory import SQLAlchemyFactory` | | Beanie `Document` | `BeanieDocumentFactory` | `from polyfactory.factories.beanie_odm_factory import BeanieDocumentFactory` | | Odmantic `Model` / `EmbeddedModel` | `OdmanticModelFactory` | `from polyfactory.factories.odmantic_odm_factory import OdmanticModelFactory` |

`polyfactory.factories.__all__` only exports `BaseFactory`, `DataclassFactory`, and `TypedDictFactory`. Always import backend-specific factories (`ModelFactory`, `MsgspecFactory`, `AttrsFactory`, `SQLAlchemyFactory`, `BeanieDocumentFactory`, `OdmanticModelFactory`) from their concrete submodules (`polyfactory.factories.pydantic_factory`, `polyfactory.factories.msgspec_factory`, `polyfactory.factories.sqlalchemy_factory`, etc.), `register_fixture` from `polyfactory.pytest_plugin`, and `post_generated` from `polyfactory.decorators` so runtime imports and `mypy`/`pyright` checks succeed.

Defining a factory

from dataclasses import dataclass
from polyfactory.factories.dataclass_factory import DataclassFactory


@dataclass
class Order:
    id: int
    customer_email: str
    total_cents: int
    status: str


class OrderFactory(DataclassFactory[Order]):
    pass


# Use it
one = OrderFactory.build()
many = OrderFactory.batch(10)

The single concrete generic argument lets Polyfactory infer `__model__`. `build()` returns one instance, `batch(n)` returns `list[T]`, `coverage()` yields the smallest set of instances that covers the model's supported variants, `create_sync()` / `create_batch_sync(n)` and `create_async()` / `create_batch_async(n)` build and persist instances, `seed_random(seed)` re-seeds the factory PRNG and Faker instance, and `add_provider(type_, fn)` registers a custom type generator.

Customizing fields

from polyfactory import Ignore, Require, Use
from polyfactory.decorators import post_generated
from polyfactory.factories import DataclassFactory


class OrderFactory(DataclassFactory[Order]):
    # Plain literal — every build returns this exact value
    status = "pending"

    # Callable — re-evaluated per build
    customer_email = Use(lambda: "test@example.com")

    # Random choice — re-evaluated per build
    total_cents = Use(DataclassFactory.__random__.randint, 100, 10_000)

    # Skip generation so the model's default / default_factory runs
    internal_note = Ignore()

    # Force callers to supply this kwarg on build() / batch() / coverage()
    tenant_id = Require()

    # Derive a field from already-generated fields on the same instance
    @post_generated
    @classmethod
    def reference(cls, id: int) -> str:
        return f"order-{id}"

`Use(callable, *args, **kwargs)` is re-invoked on every `build()`, so each generated instance gets a fresh value. `Ignore()` and `Require()` must be instantiated; omitting a `Require()` field at build time raises `MissingBuildKwargException`.

For standalone post-generation callbacks, use `PostGenerated(fn, *args, **kwargs)` where `fn` has signature `(field_name, generated_values, *args, **kwargs)`:

from typing import Any

from polyfactory import PostGenerated


def order_reference(name: str, values: dict[str, Any], prefix: str) -> str:
    return f"{prefix}-{values['id']}"


class OrderFactory(DataclassFactory[Order]):
    reference = PostGenerated(order_reference, "order")

Determinism and configuration

class OrderFactory(DataclassFactory[Order]):
    __random_seed__ = 42  # seeds cls.__random__ and cls.__faker__ at class creation


OrderFactory.seed_random(42)  # re-seed at runtime before a test or build

Set `__random_seed__` (or call `Factory.seed_random(seed)` / `__faker__.seed_instance(seed)` on a custom `__faker__ = Faker(locale="en_US")`) when test assertions depend on the exact generated values. Never pass `Faker(seed=...)` — `Faker.__init__` ignores a `seed` k

Read more
@litestar-org
Ships withlitestar

Opinionated, first-party agent skills, plugins, subagents, hooks, and rules for the Litestar framework and its ecosystem — published from a single-root repository across Google Antigravity, Claude Code, Codex CLI, Cursor, OpenCode, and VS Code / Copilot.

1720 skills1 agent
Get the whole plugin

Stars on GitHub

Momentum

stars in total
17
Star history of litestar-org/litestar-skills on GitHub, a chart by star-history.com

Other skills on litestar.

advanced-alchemy

advanced-alchemy

Use when working with advanced_alchemy, alembic/, SQLAlchemyAsyncRepositoryService, SQLAlchemyAsyncConfig, repository_type,…

litestar-autowire

litestar-autowire

Use when working with litestar_autowire, AutowirePlugin, AutowireConfig, domain_packages, AutowireIntegration, AutowireLoader, or…

litestar-build

litestar-build

Use when working with uv build, hatch build, PyApp, PYAPP_*, wheel assets, GitHub release matrices, cargo-zigbuild, or…

litestar-docs

litestar-docs

Use when working with zensical.toml, docs/conf.py, sphinx, shibuya, litestar-sphinx-theme, mkdocstrings, Griffe, objects.inv, or…

litestar-email

litestar-email

Use when working with litestar_email, EmailPlugin, EmailConfig, EmailService, EmailMessage, SMTPConfig, ResendConfig,…

More skills from other plugins.

brainstorming
Auto-invoked

brainstorming

You MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or…

@obra@obraInstall Skill
ask-matt

ask-matt

Ask which skill or flow fits your situation. A router over the skills in this repo.

skills11d309k
@mattpocock@mattpocockInstall Skill
accessibility
Auto-invoked

accessibility

Design, implement, and audit accessible UI to WCAG 2.2 Level AA across Web, iOS, and Android — semantic ARIA roles and labels,…

ecc12d293k
@affaan-m@affaan-mInstall Skill
compiler-commit

compiler-commit

Use when you want to verify compiler changes and commit with the correct convention. Runs tests, lint, and format, then commits…

react2d252k
@facebook@facebookInstall Skill

Questions about polyfactory.

Which coding agents can use polyfactory?
polyfactory installs in Claude Code, Codex, Cursor, Gemini CLI, GitHub Copilot, OpenCode and Windsurf with the skills CLI, using each agent's flag shown on this page. Flowy's auto-invocation, which fires a skill when your prompt matches, runs in Claude Code only.