Typing stubs for factory-boy

0.4.1 · active · verified Wed Apr 15

types-factory-boy is a PEP 561 type stub package that provides static type checking for the factory-boy library. It enables tools like mypy, PyCharm, and pytype to analyze code that uses factory-boy, helping to catch type-related errors before runtime. The current version is 0.4.1. As a stub package, its release cadence is tied to updates in factory-boy and improvements in its own type definitions.

Warnings

Install

Imports

Quickstart

This example demonstrates how to define a factory using `factory-boy` for a simple `NamedTuple`. When `types-factory-boy` is installed, a static type checker will use its stubs to provide type inference and validation for `UserFactory` and the generated `User` objects without needing direct imports from `types-factory-boy` itself. The `UserFactory.build()` method is correctly inferred to return an instance of `User`.

from typing import NamedTuple
import factory

class User(NamedTuple):
    id: int
    name: str
    email: str

class UserFactory(factory.Factory):
    class Meta:
        model = User

    id = factory.Sequence(lambda n: n)
    name = factory.Faker('name')
    email = factory.LazyAttribute(lambda o: f'{o.name.lower().replace(" ", ".")}@example.com')

# This code will use factory-boy at runtime.
# If types-factory-boy is installed, a type checker like mypy
# will use its stubs to verify types.
user = UserFactory.build()
print(f"Generated User: {user.name} ({user.email})")

user_explicit_type: User = UserFactory.build()
print(f"Generated User (explicitly typed): {user_explicit_type.name}")

view raw JSON →