0
# Class Definition and Decoration
1
2
Core decorators for creating attrs classes with automatic method generation. attrs provides both modern type-annotated and legacy APIs for maximum flexibility and compatibility.
3
4
## Capabilities
5
6
### Modern Class Decorators
7
8
#### Define Classes
9
Create classes with automatic method generation using type annotations and modern defaults.
10
11
```python { .api }
12
def define(
13
maybe_cls=None,
14
*,
15
these=None,
16
repr=None,
17
unsafe_hash=None,
18
hash=None,
19
init=None,
20
slots=True,
21
frozen=False,
22
weakref_slot=True,
23
str=False,
24
auto_attribs=None,
25
kw_only=False,
26
cache_hash=False,
27
auto_exc=True,
28
eq=None,
29
order=False,
30
auto_detect=True,
31
getstate_setstate=None,
32
on_setattr=None,
33
field_transformer=None,
34
match_args=True,
35
):
36
"""
37
Create a class with attrs features using modern defaults.
38
39
Parameters:
40
- these (dict, optional): Dictionary of attributes to add
41
- repr (bool, optional): Generate __repr__ method
42
- hash (bool, optional): Generate __hash__ method
43
- init (bool, optional): Generate __init__ method
44
- slots (bool): Use __slots__ for memory efficiency (default: True)
45
- frozen (bool): Make instances immutable (default: False)
46
- auto_attribs (bool, optional): Automatically detect attributes from type annotations
47
- kw_only (bool): Make all attributes keyword-only
48
- eq (bool, optional): Generate __eq__ and __ne__ methods
49
- order (bool): Generate ordering methods (__lt__, __le__, __gt__, __ge__)
50
- auto_detect (bool): Automatically determine method generation based on existing methods
51
- on_setattr (callable or list, optional): Hook(s) to run on attribute change
52
53
Returns:
54
Class or decorator function
55
"""
56
```
57
58
Usage example:
59
```python
60
@attrs.define
61
class Point:
62
x: float
63
y: float = 0.0
64
65
def distance_from_origin(self) -> float:
66
return (self.x ** 2 + self.y ** 2) ** 0.5
67
```
68
69
#### Frozen Classes
70
Create immutable classes with automatic method generation.
71
72
```python { .api }
73
def frozen(
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=True,
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
Create an immutable class with attrs features.
99
100
Similar to define() but with frozen=True by default and on_setattr=None.
101
Instances cannot be modified after creation.
102
103
Parameters: Same as define() but frozen=True by default
104
105
Returns:
106
Immutable class or decorator function
107
"""
108
```
109
110
Usage example:
111
```python
112
@attrs.frozen
113
class ImmutablePoint:
114
x: float
115
y: float
116
117
# point.x = 5 # Would raise FrozenInstanceError
118
```
119
120
#### Mutable Classes
121
Alias for define() for explicit clarity when working with both mutable and frozen classes.
122
123
```python { .api }
124
mutable = define # Alias for explicit clarity
125
```
126
127
### Legacy Class Decorators
128
129
#### attrs Decorator
130
Legacy class decorator with traditional defaults for backward compatibility.
131
132
```python { .api }
133
def attrs(
134
maybe_cls=None,
135
these=None,
136
repr_ns=None,
137
repr=None,
138
cmp=None,
139
hash=None,
140
init=None,
141
slots=False,
142
frozen=False,
143
weakref_slot=True,
144
str=False,
145
cache_hash=False,
146
auto_attribs=False,
147
kw_only=False,
148
auto_exc=False,
149
eq=None,
150
order=None,
151
auto_detect=False,
152
getstate_setstate=None,
153
on_setattr=None,
154
field_transformer=None,
155
match_args=True,
156
):
157
"""
158
Legacy class decorator with traditional defaults.
159
160
Parameters: Similar to define() but with different defaults:
161
- slots=False (vs True in define)
162
- auto_attribs=False (vs None/True in define)
163
- auto_detect=False (vs True in define)
164
165
Returns:
166
Class or decorator function
167
"""
168
```
169
170
Usage example:
171
```python
172
@attr.attrs
173
class LegacyPoint:
174
x = attr.attrib()
175
y = attr.attrib(default=0.0)
176
```
177
178
### Dynamic Class Creation
179
180
#### Make Class
181
Dynamically create attrs classes at runtime.
182
183
```python { .api }
184
def make_class(
185
name,
186
attrs,
187
bases=(object,),
188
**attributes_arguments
189
):
190
"""
191
Dynamically create a new attrs class.
192
193
Parameters:
194
- name (str): Name of the new class
195
- attrs (dict or list): Attributes to add to the class
196
- bases (tuple): Base classes
197
- **attributes_arguments: Arguments passed to attrs decorator
198
199
Returns:
200
New attrs class
201
"""
202
```
203
204
Usage example:
205
```python
206
Point = attrs.make_class("Point", ["x", "y"])
207
point = Point(1, 2)
208
209
# With more configuration
210
Person = attrs.make_class(
211
"Person",
212
{
213
"name": attrs.field(),
214
"age": attrs.field(validator=attrs.validators.instance_of(int))
215
},
216
frozen=True
217
)
218
```
219
220
### Aliases and Convenience Functions
221
222
Legacy aliases for backward compatibility:
223
224
```python { .api }
225
# In attr module
226
s = attributes = attrs # Class decorator aliases
227
dataclass = functools.partial(attrs, auto_attribs=True) # Dataclass-like interface
228
```
229
230
Usage example:
231
```python
232
# Using aliases
233
@attr.s
234
class OldStyle:
235
x = attr.ib()
236
237
@attr.dataclass
238
class DataclassStyle:
239
x: int
240
y: str = "default"
241
```
242
243
## Common Patterns
244
245
### Type Annotations with Define
246
```python
247
@attrs.define
248
class User:
249
name: str
250
age: int
251
email: str = ""
252
is_active: bool = True
253
```
254
255
### Legacy Style with Attrib
256
```python
257
@attr.attrs
258
class User:
259
name = attr.attrib()
260
age = attr.attrib()
261
email = attr.attrib(default="")
262
is_active = attr.attrib(default=True)
263
```
264
265
### Mixed Approach
266
```python
267
@attrs.define
268
class Config:
269
debug: bool = False
270
timeout: int = attrs.field(default=30, validator=attrs.validators.instance_of(int))
271
```
272
273
### Inheritance
274
```python
275
@attrs.define
276
class Animal:
277
name: str
278
species: str
279
280
@attrs.define
281
class Dog(Animal):
282
breed: str
283
species: str = "Canis lupus" # Override default
284
```