or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-polyfactory

Mock data generation factories for Python types with support for dataclasses, Pydantic, SQLAlchemy, and more

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/polyfactory@2.22.x

To install, run

npx @tessl/cli install tessl/pypi-polyfactory@2.22.0

0

# Polyfactory

1

2

Polyfactory is a comprehensive mock data generation library for Python that automatically creates realistic test data based on type hints. It supports multiple data modeling libraries including dataclasses, TypedDict, Pydantic models, msgspec structs, SQLAlchemy models, and more, enabling developers to generate complex, interrelated data structures with minimal configuration.

3

4

## Package Information

5

6

- **Package Name**: polyfactory

7

- **Language**: Python

8

- **Installation**: `pip install polyfactory`

9

- **Optional Dependencies**:

10

- `pip install polyfactory[pydantic]` - Pydantic model support

11

- `pip install polyfactory[sqlalchemy]` - SQLAlchemy model support

12

- `pip install polyfactory[full]` - All optional dependencies

13

14

## Core Imports

15

16

```python

17

from polyfactory import BaseFactory

18

from polyfactory.factories import DataclassFactory, TypedDictFactory

19

```

20

21

For specific factory types:

22

23

```python

24

from polyfactory.factories.pydantic_factory import ModelFactory

25

from polyfactory.factories.sqlalchemy_factory import SQLAlchemyFactory

26

```

27

28

Field configuration:

29

30

```python

31

from polyfactory import Use, Ignore, Require, PostGenerated

32

```

33

34

## Basic Usage

35

36

```python

37

from dataclasses import dataclass

38

from polyfactory.factories import DataclassFactory

39

40

@dataclass

41

class Person:

42

name: str

43

age: int

44

email: str

45

46

class PersonFactory(DataclassFactory[Person]):

47

__model__ = Person

48

49

# Generate single instance

50

person = PersonFactory.build()

51

print(person.name) # Generated name like "John Doe"

52

print(person.age) # Generated age like 25

53

print(person.email) # Generated email like "user@example.com"

54

55

# Generate multiple instances

56

people = PersonFactory.batch(5)

57

58

# Customize specific fields

59

person = PersonFactory.build(name="Alice", age=30)

60

```

61

62

## Architecture

63

64

Polyfactory is built around a hierarchical factory system:

65

66

- **BaseFactory**: Core factory class providing build, batch, and persistence methods

67

- **Specialized Factories**: Type-specific factories (DataclassFactory, ModelFactory, etc.)

68

- **Field Configuration**: Special field types (Use, Ignore, Require, PostGenerated) for customizing generation

69

- **Persistence Protocols**: Integration with databases and storage systems

70

- **Value Generators**: Constraint-aware generators for specialized types

71

- **Provider System**: Extensible type-to-value mapping for custom types

72

73

This architecture enables polyfactory to handle complex data generation scenarios while maintaining type safety and providing extensive customization options for any Python object model.

74

75

## Capabilities

76

77

### Core Factory Operations

78

79

Essential factory methods for building instances, batches, and managing the generation lifecycle. These methods form the foundation of all polyfactory usage patterns.

80

81

```python { .api }

82

class BaseFactory:

83

@classmethod

84

def build(cls, **kwargs) -> T: ...

85

@classmethod

86

def batch(cls, size: int, **kwargs) -> list[T]: ...

87

@classmethod

88

def coverage(cls, **kwargs) -> Iterator[T]: ...

89

```

90

91

[Factory Operations](./factory-operations.md)

92

93

### Specialized Factory Classes

94

95

Type-specific factory implementations for different Python object modeling libraries, each optimized for their respective type systems and features.

96

97

```python { .api }

98

class DataclassFactory(BaseFactory[T]): ...

99

class TypedDictFactory(BaseFactory[TypedDictT]): ...

100

class ModelFactory(BaseFactory[T]): ... # Pydantic

101

class SQLAlchemyFactory(BaseFactory[T]): ...

102

```

103

104

[Specialized Factories](./specialized-factories.md)

105

106

### Field Configuration

107

108

Special field types and decorators that control how individual attributes are generated, providing fine-grained control over the data generation process.

109

110

```python { .api }

111

class Use: ...

112

class Ignore: ...

113

class Require: ...

114

class PostGenerated: ...

115

```

116

117

[Field Configuration](./field-configuration.md)

118

119

### Persistence Integration

120

121

Protocols and handlers for persisting generated data to databases and storage systems, supporting both synchronous and asynchronous operations.

122

123

```python { .api }

124

class SyncPersistenceProtocol: ...

125

class AsyncPersistenceProtocol: ...

126

```

127

128

[Persistence](./persistence.md)

129

130

### Provider System and Customization

131

132

Extensible system for registering custom value generators and configuring the factory behavior for specific types and use cases.

133

134

```python { .api }

135

@classmethod

136

def add_provider(cls, type_: type, provider: Callable): ...

137

@classmethod

138

def seed_random(cls, seed: int): ...

139

```

140

141

[Customization](./customization.md)

142

143

## Types

144

145

```python { .api }

146

# Configuration attributes for factory classes

147

__model__: type # The model type for the factory

148

__faker__: Faker # Faker instance for data generation

149

__random__: Random # Random instance for randomization

150

__sync_persistence__: SyncPersistenceProtocol | None

151

__async_persistence__: AsyncPersistenceProtocol | None

152

__randomize_collection_length__: bool

153

__min_collection_length__: int

154

__max_collection_length__: int

155

__allow_none_optionals__: bool

156

__use_defaults__: bool

157

__check_model__: bool

158

159

# Exception types

160

class ConfigurationException(Exception): ...

161

class ParameterException(Exception): ...

162

class MissingBuildKwargException(Exception): ...

163

```