0
# Core API
1
2
The fundamental cattrs API for converting between structured and unstructured data. This module provides the primary functions and classes that form the backbone of cattrs functionality.
3
4
## Capabilities
5
6
### Module-Level Functions
7
8
Functions that use the global converter instance for simple, direct usage without requiring converter instantiation.
9
10
```python { .api }
11
def structure(obj, cl):
12
"""
13
Convert unstructured data to structured data using the global converter.
14
15
Parameters:
16
- obj: The unstructured data to convert
17
- cl: The class or type to structure into
18
19
Returns:
20
Structured instance of the specified class
21
"""
22
23
def unstructure(obj, unstructure_as=None):
24
"""
25
Convert structured data to unstructured data using the global converter.
26
27
Parameters:
28
- obj: The structured object to convert
29
- unstructure_as: Optional type to unstructure as
30
31
Returns:
32
Unstructured data (typically dict or primitive types)
33
"""
34
35
def structure_attrs_fromdict(dict_obj, cl):
36
"""
37
Structure attrs classes from dictionaries using the global converter.
38
39
Parameters:
40
- dict_obj: Dictionary to structure from
41
- cl: attrs class to structure into
42
43
Returns:
44
Instance of the attrs class
45
"""
46
47
def structure_attrs_fromtuple(tuple_obj, cl):
48
"""
49
Structure attrs classes from tuples using the global converter.
50
51
Parameters:
52
- tuple_obj: Tuple to structure from
53
- cl: attrs class to structure into
54
55
Returns:
56
Instance of the attrs class
57
"""
58
```
59
60
### Converter Classes
61
62
Core converter classes that provide the main structuring and unstructuring functionality.
63
64
```python { .api }
65
class BaseConverter:
66
"""
67
Base class for all converters that handles structured/unstructured data conversion.
68
69
Provides the foundation for the converter system but should not be instantiated directly.
70
"""
71
def __init__(self):
72
"""Initialize the base converter."""
73
74
class Converter(BaseConverter):
75
"""
76
Main converter class with specialized un/structuring functions and advanced features.
77
78
Provides customizable hooks, strategies, and optimization options for data conversion.
79
"""
80
def __init__(
81
self,
82
dict_factory=dict,
83
unstruct_strat=UnstructureStrategy.AS_DICT,
84
omit_if_default=False,
85
forbid_extra_keys=False,
86
type_overrides=None,
87
unstruct_collection_overrides=None,
88
prefer_attrib_converters=False,
89
detailed_validation=True,
90
unstructure_fallback_factory=lambda _: identity,
91
structure_fallback_factory=lambda t: raise_error(None, t),
92
use_alias=False
93
):
94
"""
95
Initialize a converter with customization options.
96
97
Parameters:
98
- dict_factory: Factory function for creating dictionaries
99
- unstruct_strat: Default unstructuring strategy
100
- omit_if_default: Omit fields with default values during unstructuring
101
- forbid_extra_keys: Whether to forbid extra keys during structuring
102
- type_overrides: Mapping of type overrides for attribute handling
103
- unstruct_collection_overrides: Mapping of collection unstructure overrides
104
- prefer_attrib_converters: Use attribute-level converters when available
105
- detailed_validation: Enable detailed validation error messages
106
- unstructure_fallback_factory: Factory for unstructuring hooks when no match
107
- structure_fallback_factory: Factory for structuring hooks when no match
108
- use_alias: Use field alias instead of field name as dictionary key
109
"""
110
111
def structure(self, obj, cl):
112
"""
113
Convert unstructured data to a structured class instance.
114
115
Parameters:
116
- obj: Unstructured data to convert
117
- cl: Class or type to structure into
118
119
Returns:
120
Instance of the specified class
121
"""
122
123
def unstructure(self, obj, unstructure_as=None):
124
"""
125
Convert a structured object to unstructured data.
126
127
Parameters:
128
- obj: Structured object to convert
129
- unstructure_as: Optional type to unstructure as
130
131
Returns:
132
Unstructured data representation
133
"""
134
135
def structure_attrs_fromdict(self, dict_obj, cl):
136
"""Structure attrs classes from dictionaries."""
137
138
def structure_attrs_fromtuple(self, tuple_obj, cl):
139
"""Structure attrs classes from tuples."""
140
141
# Type alias for backward compatibility
142
GenConverter = Converter
143
```
144
145
### Hook Registration
146
147
Functions for registering custom structuring and unstructuring hooks with converters.
148
149
```python { .api }
150
def register_structure_hook(cl, func=None):
151
"""
152
Register a structure hook for a specific type on the global converter.
153
154
Parameters:
155
- cl: The class or type to register the hook for
156
- func: The hook function to register (can be used as decorator if None)
157
158
Returns:
159
The hook function (when used as decorator) or None
160
"""
161
162
def register_structure_hook_func(check_func, func):
163
"""
164
Register a structure hook using a predicate function on the global converter.
165
166
Parameters:
167
- check_func: Function that returns True for types this hook handles
168
- func: The hook function to register
169
"""
170
171
def register_unstructure_hook(cl, func=None):
172
"""
173
Register an unstructure hook for a specific type on the global converter.
174
175
Parameters:
176
- cl: The class or type to register the hook for
177
- func: The hook function to register (can be used as decorator if None)
178
179
Returns:
180
The hook function (when used as decorator) or None
181
"""
182
183
def register_unstructure_hook_func(check_func, func):
184
"""
185
Register an unstructure hook using a predicate function on the global converter.
186
187
Parameters:
188
- check_func: Function that returns True for types this hook handles
189
- func: The hook function to register
190
"""
191
192
def get_structure_hook(cl, cache_result=True):
193
"""
194
Get the structure hook for a given type from the global converter.
195
196
Parameters:
197
- cl: The class or type to get the hook for
198
- cache_result: Whether to cache the result for performance
199
200
Returns:
201
The structure hook function for the type
202
"""
203
204
def get_unstructure_hook(cl, cache_result=True):
205
"""
206
Get the unstructure hook for a given type from the global converter.
207
208
Parameters:
209
- cl: The class or type to get the hook for
210
- cache_result: Whether to cache the result for performance
211
212
Returns:
213
The unstructure hook function for the type
214
"""
215
```
216
217
### Global Converter
218
219
The global converter instance used by module-level functions.
220
221
```python { .api }
222
global_converter: Converter
223
"""The global converter instance used by module-level functions."""
224
```
225
226
### Usage Examples
227
228
#### Basic Structuring and Unstructuring
229
230
```python
231
from cattrs import structure, unstructure
232
from attrs import define
233
from typing import List
234
235
@define
236
class User:
237
name: str
238
age: int
239
tags: List[str]
240
241
# Create structured data
242
user = User(name="Alice", age=30, tags=["admin", "user"])
243
244
# Unstructure to dictionary
245
user_dict = unstructure(user)
246
# Result: {'name': 'Alice', 'age': 30, 'tags': ['admin', 'user']}
247
248
# Structure back to class
249
user_copy = structure(user_dict, User)
250
# Result: User(name='Alice', age=30, tags=['admin', 'user'])
251
```
252
253
#### Custom Converter Usage
254
255
```python
256
from cattrs import Converter, UnstructureStrategy
257
258
# Create custom converter with specific settings
259
converter = Converter(
260
dict_factory=dict,
261
unstruct_strat=UnstructureStrategy.AS_DICT,
262
forbid_extra_keys=True
263
)
264
265
# Use custom converter
266
data = converter.unstructure(user)
267
user_copy = converter.structure(data, User)
268
```
269
270
#### Hook Registration
271
272
```python
273
from cattrs import register_structure_hook, register_unstructure_hook
274
from datetime import datetime
275
276
# Register hooks for datetime handling
277
def structure_datetime(timestamp_str, _):
278
return datetime.fromisoformat(timestamp_str)
279
280
def unstructure_datetime(dt):
281
return dt.isoformat()
282
283
register_structure_hook(datetime, structure_datetime)
284
register_unstructure_hook(datetime, unstructure_datetime)
285
286
# Now datetime objects will be handled automatically
287
@define
288
class Event:
289
name: str
290
timestamp: datetime
291
292
event = Event("Meeting", datetime.now())
293
event_dict = unstructure(event) # timestamp becomes ISO string
294
event_copy = structure(event_dict, Event) # string becomes datetime
295
```
296
297
## Types
298
299
```python { .api }
300
from typing import TypeVar, Any, Callable, Dict, Optional, Mapping
301
from enum import Enum
302
from cattrs.fns import identity, raise_error
303
from cattrs.gen import AttributeOverride
304
305
T = TypeVar('T')
306
307
class UnstructureStrategy(Enum):
308
"""Enum defining unstructuring strategies."""
309
AS_DICT = "AS_DICT"
310
AS_TUPLE = "AS_TUPLE"
311
312
# Hook function types
313
StructureHook = Callable[[Any, type[T]], T]
314
UnstructureHook = Callable[[T], Any]
315
PredicateFunc = Callable[[type], bool]
316
HookFactory = Callable[[type], Any]
317
```