0
# Specialized Factories
1
2
Type-specific factory implementations optimized for different Python object modeling libraries. Each factory class is designed to work with the specific features and constraints of its target type system.
3
4
## Capabilities
5
6
### Dataclass Factory
7
8
Factory implementation for Python dataclasses with support for all dataclass features including default values, field metadata, and inheritance.
9
10
```python { .api }
11
class DataclassFactory(BaseFactory[T]):
12
"""
13
Base factory for Python dataclass types.
14
15
Automatically handles dataclass field types, defaults, and metadata.
16
Supports inheritance and complex nested dataclass structures.
17
"""
18
```
19
20
**Usage Example:**
21
```python
22
from dataclasses import dataclass, field
23
from polyfactory.factories import DataclassFactory
24
25
@dataclass
26
class Address:
27
street: str
28
city: str
29
zip_code: str
30
31
@dataclass
32
class Person:
33
name: str
34
age: int = 25
35
addresses: list[Address] = field(default_factory=list)
36
37
class PersonFactory(DataclassFactory[Person]):
38
__model__ = Person
39
40
# Generates Person with Address objects in the addresses list
41
person = PersonFactory.build()
42
```
43
44
### TypedDict Factory
45
46
Factory implementation for TypedDict types with support for total/partial typing and inheritance.
47
48
```python { .api }
49
class TypedDictFactory(BaseFactory[TypedDictT]):
50
"""
51
Base factory for TypedDict types.
52
53
Handles required and optional keys based on TypedDict total setting.
54
Supports TypedDict inheritance and nested structures.
55
"""
56
```
57
58
**Usage Example:**
59
```python
60
from typing import TypedDict, NotRequired
61
from polyfactory.factories import TypedDictFactory
62
63
class UserDict(TypedDict):
64
id: int
65
name: str
66
email: NotRequired[str] # Optional field
67
68
class UserDictFactory(TypedDictFactory[UserDict]):
69
__model__ = UserDict
70
71
user = UserDictFactory.build() # May or may not include 'email'
72
```
73
74
### Pydantic Model Factory
75
76
Factory implementation for Pydantic models with support for both v1 and v2, including validators, field constraints, and computed fields.
77
78
```python { .api }
79
class ModelFactory(BaseFactory[T]):
80
"""
81
Base factory for Pydantic models (v1 and v2 compatible).
82
83
Respects Pydantic field constraints, validators, and default values.
84
Handles nested models, unions, and complex validation scenarios.
85
"""
86
```
87
88
**Usage Example:**
89
```python
90
from pydantic import BaseModel, EmailStr, Field
91
from polyfactory.factories.pydantic_factory import ModelFactory
92
93
class User(BaseModel):
94
name: str = Field(min_length=2, max_length=50)
95
email: EmailStr
96
age: int = Field(ge=0, le=120)
97
98
class UserFactory(ModelFactory[User]):
99
__model__ = User
100
101
# Generates valid User respecting all Pydantic constraints
102
user = UserFactory.build()
103
```
104
105
### SQLAlchemy Factory
106
107
Factory implementation for SQLAlchemy ORM models with support for relationships, constraints, and database-specific types.
108
109
```python { .api }
110
class SQLAlchemyFactory(BaseFactory[T]):
111
"""
112
Base factory for SQLAlchemy ORM models.
113
114
Handles SQLAlchemy column types, relationships, and constraints.
115
Integrates with persistence handlers for database operations.
116
"""
117
```
118
119
**Usage Example:**
120
```python
121
from sqlalchemy import Column, Integer, String, ForeignKey
122
from sqlalchemy.ext.declarative import declarative_base
123
from sqlalchemy.orm import relationship
124
from polyfactory.factories.sqlalchemy_factory import SQLAlchemyFactory
125
126
Base = declarative_base()
127
128
class User(Base):
129
__tablename__ = 'users'
130
id = Column(Integer, primary_key=True)
131
name = Column(String(50))
132
posts = relationship("Post", back_populates="author")
133
134
class Post(Base):
135
__tablename__ = 'posts'
136
id = Column(Integer, primary_key=True)
137
title = Column(String(100))
138
author_id = Column(Integer, ForeignKey('users.id'))
139
author = relationship("User", back_populates="posts")
140
141
class UserFactory(SQLAlchemyFactory[User]):
142
__model__ = User
143
144
class PostFactory(SQLAlchemyFactory[Post]):
145
__model__ = Post
146
147
user = UserFactory.build() # Generates User with related Posts
148
```
149
150
### Attrs Factory
151
152
Factory implementation for attrs classes with support for validators, converters, and metadata.
153
154
```python { .api }
155
class AttrsFactory(BaseFactory[T]):
156
"""
157
Base factory for attrs classes.
158
159
Handles attrs field definitions, validators, converters, and default values.
160
Supports attrs inheritance and complex attribute configurations.
161
"""
162
```
163
164
**Usage Example:**
165
```python
166
import attrs
167
from polyfactory.factories.attrs_factory import AttrsFactory
168
169
@attrs.define
170
class Person:
171
name: str
172
age: int = attrs.field(validator=attrs.validators.instance_of(int))
173
email: str = attrs.field(converter=str.lower)
174
175
class PersonFactory(AttrsFactory[Person]):
176
__model__ = Person
177
178
person = PersonFactory.build() # Respects attrs validators and converters
179
```
180
181
### Msgspec Factory
182
183
Factory implementation for msgspec structs with support for constraints and custom encoders/decoders.
184
185
```python { .api }
186
class MsgspecFactory(BaseFactory[T]):
187
"""
188
Base factory for msgspec structs.
189
190
Handles msgspec field constraints and type annotations.
191
Supports msgspec's high-performance serialization features.
192
"""
193
```
194
195
**Usage Example:**
196
```python
197
import msgspec
198
from polyfactory.factories.msgspec_factory import MsgspecFactory
199
200
class User(msgspec.Struct):
201
name: str
202
age: int
203
email: str
204
205
class UserFactory(MsgspecFactory[User]):
206
__model__ = User
207
208
user = UserFactory.build()
209
```
210
211
### Beanie Document Factory
212
213
Factory implementation for Beanie ODM documents with support for MongoDB-specific features and validation.
214
215
```python { .api }
216
class BeanieDocumentFactory(ModelFactory[T]):
217
"""
218
Factory for Beanie ODM documents.
219
220
Extends ModelFactory with Beanie-specific document features.
221
Handles MongoDB ObjectId generation and document relationships.
222
"""
223
```
224
225
**Usage Example:**
226
```python
227
from beanie import Document
228
from polyfactory.factories.beanie_odm_factory import BeanieDocumentFactory
229
230
class User(Document):
231
name: str
232
email: str
233
age: int
234
235
class UserFactory(BeanieDocumentFactory[User]):
236
__model__ = User
237
238
user = UserFactory.build() # Includes valid ObjectId
239
```
240
241
### Odmantic Model Factory
242
243
Factory implementation for Odmantic ODM models with support for MongoDB integration through Pydantic.
244
245
```python { .api }
246
class OdmanticModelFactory(ModelFactory[T]):
247
"""
248
Factory for Odmantic ODM models.
249
250
Extends ModelFactory with Odmantic-specific model features.
251
Handles MongoDB document generation and model relationships.
252
"""
253
```
254
255
**Usage Example:**
256
```python
257
from odmantic import Model
258
from polyfactory.factories.odmantic_odm_factory import OdmanticModelFactory
259
260
class User(Model):
261
name: str
262
email: str
263
age: int
264
265
class UserFactory(OdmanticModelFactory[User]):
266
__model__ = User
267
268
user = UserFactory.build()
269
```
270
271
## Factory Configuration
272
273
All specialized factories inherit common configuration attributes from BaseFactory:
274
275
```python { .api }
276
# Common configuration attributes
277
__model__: type # Required: The model type for the factory
278
__faker__: Faker # Faker instance for generating realistic data
279
__random__: Random # Random instance for deterministic generation
280
__randomize_collection_length__: bool # Randomize collection sizes
281
__min_collection_length__: int # Minimum collection size
282
__max_collection_length__: int # Maximum collection size
283
__allow_none_optionals__: bool # Allow None values for optional fields
284
__use_defaults__: bool # Use model default values when available
285
__check_model__: bool # Validate generated instances
286
```