Typing stubs for factory-boy
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
- breaking factory-boy 3.0.0 introduced significant breaking changes, including the deprecation and removal of `FACTORY_FOR`, `ABSTRACT_FACTORY`, `FACTORY_STRATEGY`, `FACTORY_ARG_PARAMETERS`, and `FACTORY_HIDDEN_ARGS` in favor of `Meta` class attributes like `model`, `abstract`, `strategy`, `inline_args`, and `exclude` respectively. Types-factory-boy reflects these changes.
- breaking The separation of ORM-specific factories (e.g., `DjangoModelFactory`, `SQLAlchemyModelFactory`) into their own modules (`factory.django`, `factory.alchemy`) occurred in older `factory-boy` versions. While `types-factory-boy` handles these imports correctly, older codebases might have incorrect import paths for these specialized factories.
- gotcha When using `factory-boy` and `types-factory-boy`, type checkers might sometimes struggle with the inferred return types of `Factory()` or `Factory.build()` when `stub` strategy is implicitly or explicitly used. By default, `Factory()` might sometimes return a `StubObject` which lacks the methods/attributes of the actual model.
- gotcha Changes related to type annotations were introduced directly in `factory-boy` 3.3.3, which could cause breaking changes in existing pipelines due to more strict type checking. While `types-factory-boy` aims to provide correct stubs, discrepancies or new strictness from the runtime library's own annotations can lead to type errors.
Install
-
pip install types-factory-boy
Imports
- Factory
from factory import Factory
- DjangoModelFactory
from factory.django import DjangoModelFactory
- Sequence
from factory import Sequence
Quickstart
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}")