0
# attrs
1
2
Classes Without Boilerplate - A Python library that brings back the joy of writing classes by relieving you from the drudgery of implementing object protocols (dunder methods). It provides declarative attribute definitions that automatically generate concise and correct code including `__repr__`, equality-checking methods, initializers, and much more without writing boilerplate code.
3
4
## Package Information
5
6
- **Package Name**: attrs
7
- **Language**: Python
8
- **Installation**: `pip install attrs`
9
- **License**: MIT
10
- **Documentation**: https://www.attrs.org/
11
12
## Core Imports
13
14
Modern API (recommended):
15
```python
16
import attrs
17
```
18
19
Legacy API (also available):
20
```python
21
import attr
22
```
23
24
Common patterns:
25
```python
26
from attrs import define, field, validators, converters, filters
27
from functools import partial
28
```
29
30
## Basic Usage
31
32
```python
33
import attrs
34
35
@attrs.define
36
class Person:
37
name: str
38
age: int = attrs.field(validator=attrs.validators.instance_of(int))
39
email: str = ""
40
41
# Automatically gets __init__, __repr__, __eq__, etc.
42
person = Person("Alice", 30, "alice@example.com")
43
print(person) # Person(name='Alice', age=30, email='alice@example.com')
44
45
# Create modified copy
46
older_person = attrs.evolve(person, age=31)
47
print(older_person) # Person(name='Alice', age=31, email='alice@example.com')
48
49
# Convert to dict
50
person_dict = attrs.asdict(person)
51
print(person_dict) # {'name': 'Alice', 'age': 30, 'email': 'alice@example.com'}
52
```
53
54
## Architecture
55
56
attrs provides both modern (`attrs`) and legacy (`attr`) APIs with the same underlying functionality:
57
58
- **Class Decorators**: Transform regular classes into feature-rich data classes
59
- **Field Definitions**: Declarative attribute configuration with validation, conversion, and metadata
60
- **Automatic Methods**: Generate `__init__`, `__repr__`, `__eq__`, `__hash__`, `__lt__`, etc.
61
- **Extensibility**: Custom validators, converters, and setters for complex behaviors
62
- **Introspection**: Runtime access to class metadata and field information
63
64
The library is designed for maximum reusability, supports both modern type-annotated and classic APIs, and maintains high performance without runtime penalties.
65
66
## Capabilities
67
68
### Class Definition and Decoration
69
70
Core decorators for creating attrs classes with automatic method generation, including modern type-annotated and legacy approaches.
71
72
```python { .api }
73
def define(
74
maybe_cls=None,
75
*,
76
these=None,
77
repr=None,
78
unsafe_hash=None,
79
hash=None,
80
init=None,
81
slots=True,
82
frozen=False,
83
weakref_slot=True,
84
str=False,
85
auto_attribs=None,
86
kw_only=False,
87
cache_hash=False,
88
auto_exc=True,
89
eq=None,
90
order=False,
91
auto_detect=True,
92
getstate_setstate=None,
93
on_setattr=None,
94
field_transformer=None,
95
match_args=True,
96
): ...
97
98
# frozen is a partial function of define with frozen=True, on_setattr=None
99
frozen = partial(define, frozen=True, on_setattr=None)
100
101
def attrs(
102
maybe_cls=None,
103
these=None,
104
repr_ns=None,
105
repr=None,
106
cmp=None,
107
hash=None,
108
init=None,
109
slots=False,
110
frozen=False,
111
weakref_slot=True,
112
str=False,
113
auto_attribs=False,
114
kw_only=False,
115
cache_hash=False,
116
auto_exc=False,
117
eq=None,
118
order=None,
119
auto_detect=False,
120
collect_by_mro=True,
121
getstate_setstate=None,
122
on_setattr=None,
123
field_transformer=None,
124
match_args=True,
125
unsafe_hash=None,
126
): ...
127
```
128
129
[Class Definition](./class-definition.md)
130
131
### Field Definition and Configuration
132
133
Define attributes with validation, conversion, default values, and metadata using both modern and legacy APIs.
134
135
```python { .api }
136
def field(
137
*,
138
default=NOTHING,
139
validator=None,
140
repr=True,
141
hash=None,
142
init=True,
143
metadata=None,
144
type=None,
145
converter=None,
146
factory=None,
147
kw_only=False,
148
eq=None,
149
order=None,
150
on_setattr=None,
151
alias=None,
152
): ...
153
154
def attrib(
155
default=NOTHING,
156
validator=None,
157
repr=True,
158
cmp=None,
159
hash=None,
160
init=True,
161
metadata=None,
162
type=None,
163
converter=None,
164
factory=None,
165
kw_only=False,
166
eq=None,
167
order=None,
168
on_setattr=None,
169
alias=None,
170
*,
171
# Legacy parameters
172
convert=None,
173
): ...
174
```
175
176
[Field Configuration](./field-configuration.md)
177
178
### Validation and Conversion
179
180
Comprehensive validation and conversion system with built-in validators, converters, and combinators for complex data processing.
181
182
```python { .api }
183
# Validators
184
def instance_of(type): ...
185
def optional(validator): ...
186
def in_(options): ...
187
188
# Converters
189
def optional(converter): ...
190
def default_if_none(default): ...
191
def pipe(*converters): ...
192
```
193
194
[Validation and Conversion](./validation-conversion.md)
195
196
### Utilities and Introspection
197
198
Functions for working with attrs classes including serialization, introspection, and instance manipulation.
199
200
```python { .api }
201
def asdict(inst, *, recurse=True, filter=None, **kwargs): ...
202
def astuple(inst, *, recurse=True, filter=None): ...
203
def fields(cls): ...
204
def fields_dict(cls): ...
205
def has(cls): ...
206
def evolve(*args, **changes): ...
207
def assoc(inst, **changes): ... # Deprecated, use evolve instead
208
def make_class(name, attrs, bases=(), **attrs_kwargs): ...
209
def resolve_types(cls, globalns=None, localns=None, attribs=None, include_extras=True): ...
210
def validate(inst): ...
211
```
212
213
[Utilities](./utilities.md)
214
215
### Filters
216
217
Functions for creating filters used with `asdict()` and `astuple()` to control which attributes are included or excluded during serialization.
218
219
```python { .api }
220
def include(*what): ... # Create filter that only allows specified types/names/attributes
221
def exclude(*what): ... # Create filter that excludes specified types/names/attributes
222
```
223
224
### Configuration and Error Handling
225
226
Configuration options and comprehensive exception hierarchy for error handling in attrs applications.
227
228
```python { .api }
229
# Exceptions
230
class NotAnAttrsClassError(ValueError): ...
231
class FrozenInstanceError(AttributeError): ...
232
class AttrsAttributeNotFoundError(ValueError): ...
233
234
# Configuration
235
def set_run_validators(run: bool): ... # Deprecated
236
def get_run_validators(): ... # Deprecated
237
```
238
239
[Configuration and Errors](./configuration-errors.md)
240
241
## Constants and Types
242
243
```python { .api }
244
# Constants
245
NOTHING: NothingType # Sentinel for missing values
246
247
# Core Classes
248
class Attribute:
249
name: str
250
default: Any
251
validator: Optional[Callable]
252
converter: Optional[Callable]
253
# ... additional properties
254
255
class Factory:
256
factory: Callable
257
takes_self: bool = False
258
259
class Converter:
260
converter: Callable
261
takes_self: bool = False
262
takes_field: bool = False
263
264
# Type Definitions
265
AttrsInstance = Protocol # Protocol for attrs instances
266
NothingType = Literal[NOTHING] # Type for NOTHING sentinel
267
```