or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

code-generation.mdcore-api.mderror-handling.mdindex.mdpreconf-converters.mdstrategies.md

index.mddocs/

0

# Cattrs

1

2

Cattrs is a Swiss Army knife for (un)structuring and validating data in Python. It converts unstructured dictionaries into proper classes and back, while validating their contents. Built on the principle of separating un/structuring rules from data models, cattrs excels at recursive handling of complex nested data structures and provides extensive customization options.

3

4

## Package Information

5

6

- **Package Name**: cattrs

7

- **Language**: Python

8

- **Installation**: `pip install cattrs`

9

10

## Core Imports

11

12

```python

13

import cattrs

14

```

15

16

Common imports for direct usage:

17

18

```python

19

from cattrs import structure, unstructure

20

```

21

22

For creating custom converters:

23

24

```python

25

from cattrs import Converter

26

```

27

28

## Basic Usage

29

30

```python

31

from attrs import define

32

from cattrs import structure, unstructure

33

34

@define

35

class Person:

36

name: str

37

age: int

38

email: str | None = None

39

40

# Unstructure: Convert class instance to dictionary

41

person = Person(name="Alice", age=30, email="alice@example.com")

42

data = unstructure(person)

43

print(data) # {'name': 'Alice', 'age': 30, 'email': 'alice@example.com'}

44

45

# Structure: Convert dictionary to class instance

46

person_copy = structure(data, Person)

47

print(person_copy) # Person(name='Alice', age=30, email='alice@example.com')

48

49

# Works with complex nested structures

50

@define

51

class Team:

52

name: str

53

members: list[Person]

54

55

team_data = {

56

'name': 'Engineering',

57

'members': [

58

{'name': 'Alice', 'age': 30, 'email': 'alice@example.com'},

59

{'name': 'Bob', 'age': 25, 'email': None}

60

]

61

}

62

63

team = structure(team_data, Team)

64

print(team.members[0].name) # Alice

65

```

66

67

## Architecture

68

69

Cattrs is built around a converter-based architecture that enables flexible data transformation:

70

71

- **Global Converter**: Default converter instance (`cattrs.global_converter`) used by module-level functions

72

- **Custom Converters**: User-created `Converter` instances for specialized use cases

73

- **Hook System**: Registration system for custom structuring/unstructuring logic

74

- **Pre-configured Converters**: Ready-to-use converters for specific serialization formats

75

- **Code Generation**: Dynamic function generation for optimized performance

76

77

This design allows cattrs to handle complex type hierarchies while maintaining excellent performance and providing extensive customization options for edge cases.

78

79

## Capabilities

80

81

### Core Structuring and Unstructuring

82

83

The fundamental cattrs API for converting between structured and unstructured data. Provides module-level functions that use the global converter, as well as converter classes for custom configurations.

84

85

```python { .api }

86

def structure(obj, cl, converter=None):

87

"""Convert unstructured data to structured data."""

88

89

def unstructure(obj, unstructure_as=None, converter=None):

90

"""Convert structured data to unstructured data."""

91

92

class Converter:

93

"""Main converter class with specialized un/structuring functions."""

94

def __init__(self, **kwargs): ...

95

def structure(self, obj, cl): ...

96

def unstructure(self, obj, unstructure_as=None): ...

97

```

98

99

[Core API](./core-api.md)

100

101

### Pre-configured Converters

102

103

Ready-to-use converters pre-configured for specific serialization formats including JSON, YAML, MessagePack, TOML, BSON, CBOR2, and more. Each provides optimal settings and type handling for their respective formats.

104

105

```python { .api }

106

# JSON converter example

107

from cattrs.preconf.json import make_converter

108

109

converter = make_converter()

110

json_data = converter.unstructure(obj)

111

obj_copy = converter.structure(json_data, MyClass)

112

```

113

114

[Pre-configured Converters](./preconf-converters.md)

115

116

### Advanced Strategies and Customization

117

118

Powerful strategies for handling complex type scenarios including union types, subclass hierarchies, and class method integration. Provides tools for configuring converters to handle advanced typing patterns.

119

120

```python { .api }

121

from cattrs.strategies import configure_tagged_union, include_subclasses

122

123

def configure_tagged_union(union_type, converter, **kwargs): ...

124

def include_subclasses(base_class, converter, **kwargs): ...

125

```

126

127

[Strategies and Customization](./strategies.md)

128

129

### Error Handling and Validation

130

131

Comprehensive error handling system with detailed validation errors, structured exception hierarchies, and error transformation utilities for better debugging and user feedback.

132

133

```python { .api }

134

class BaseValidationError(ExceptionGroup):

135

"""Base class for validation errors."""

136

137

def transform_error(exc, path=None, **kwargs):

138

"""Transform validation errors into detailed error messages."""

139

```

140

141

[Error Handling](./error-handling.md)

142

143

### Code Generation and Optimization

144

145

High-performance code generation utilities for creating specialized structuring and unstructuring functions. Enables optimization of performance-critical code paths.

146

147

```python { .api }

148

from cattrs.gen import make_dict_structure_fn, make_dict_unstructure_fn

149

150

def make_dict_structure_fn(cl, converter, **kwargs): ...

151

def make_dict_unstructure_fn(cl, converter, **kwargs): ...

152

```

153

154

[Code Generation](./code-generation.md)

155

156

## Types

157

158

```python { .api }

159

from typing import Protocol, TypeVar, Any, Callable

160

from enum import Enum

161

162

T = TypeVar('T')

163

164

class SimpleStructureHook(Protocol):

165

"""Protocol for structure hooks with optional second argument."""

166

def __call__(self, val: Any, type: type[T] = None) -> T: ...

167

168

class UnstructureStrategy(Enum):

169

"""Enum defining unstructuring strategies."""

170

AS_DICT = "AS_DICT"

171

AS_TUPLE = "AS_TUPLE"

172

173

# Type aliases for hook functions

174

StructureHook = Callable[[Any, type[T]], T]

175

UnstructureHook = Callable[[T], Any]

176

```