Debian Codegraph @

testing/web-platform/tests/tools/third_party/attrs/docs/init.md

raw
1 # Initialization
2
3 In Python, instance initialization happens in the `__init__` method.
4 Generally speaking, you should keep as little logic as possible in it, and you should think about what the class needs and not how it is going to be instantiated.
5
6 Passing complex objects into `__init__` and then using them to derive data for the class unnecessarily couples your new class with the old class which makes it harder to test and also will cause problems later.
7
8 So assuming you use an ORM and want to extract 2D points from a row object, do not write code like this:
9
10 ```python
11 class Point:
12 def __init__(self, database_row):
13 self.x = database_row.x
14 self.y = database_row.y
15
16 pt = Point(row)
17 ```
18
19 Instead, write a {obj}`classmethod` that will extract it for you:
20
21 ```python
22 @define
23 class Point:
24 x: float
25 y: float
26
27 @classmethod
28 def from_row(cls, row):
29 return cls(row.x, row.y)
30
31 pt = Point.from_row(row)
32 ```
33
34 Now you can instantiate `Point`s without creating fake row objects in your tests and you can have as many smart creation helpers as you want, in case more data sources appear.
35
36 For similar reasons, we strongly discourage from patterns like:
37
38 ```python
39 pt = Point(**row.attributes)
40 ```
41
42 which couples your classes to the database data model.
43 Try to design your classes in a way that is clean and convenient to use -- not based on your database format.
44 The database format can change anytime and you're stuck with a bad class design that is hard to change.
45 Embrace functions and classmethods as a filter between reality and what's best for you to work with.
46
47 :::{warning}
48 While *attrs*'s initialization concepts (including the following sections about validators and converters) are powerful, they are **not** intended to replace a fully-featured serialization or validation system.
49
50 We want to help you to write a `__init__` that you'd write by hand, but with less boilerplate.
51
52 If you look for powerful-yet-unintrusive serialization and validation for your *attrs* classes, have a look at our sibling project [*cattrs*](https://catt.rs/) or our [third-party extensions](https://github.com/python-attrs/attrs/wiki/Extensions-to-attrs).
53 :::
54
55 (private-attributes)=
56
57 ## Private Attributes and Aliases
58
59 One thing people tend to find confusing is the treatment of private attributes that start with an underscore.
60 *attrs* follows the doctrine that [there is no such thing as a private argument](https://github.com/hynek/characteristic/issues/6) and strips the underscores from the name when writing the `__init__` method signature:
61
62 ```{doctest}
63 >>> import inspect
64 >>> from attrs import define
65 >>> @define
66 ... class C:
67 ... _x: int
68 >>> inspect.signature(C.__init__)
69 <Signature (self, x: int) -> None>
70 ```
71
72 There really isn't a right or wrong, it's a matter of taste.
73 But it's important to be aware of it because it can lead to surprising syntax errors:
74
75 ```{doctest}
76 >>> @define
77 ... class C:
78 ... _1: int
79 Traceback (most recent call last):
80 ...
81 SyntaxError: invalid syntax
82 ```
83
84 In this case a valid attribute name `_1` got transformed into an invalid argument name `1`.
85
86 If your taste differs, you can use the *alias* argument to {func}`attrs.field` to explicitly set the argument name.
87 This can be used to override private attribute handling, or make other arbitrary changes to `__init__` argument names.
88
89 ```{doctest}
90 >>> from attrs import field
91 >>> @define
92 ... class C:
93 ... _x: int = field(alias="_x")
94 ... y: int = field(alias="distasteful_y")
95 >>> inspect.signature(C.__init__)
96 <Signature (self, _x: int, distasteful_y: int) -> None>
97 ```
98
99 (defaults)=
100
101 ## Defaults
102
103 Sometimes you don't want to pass all attribute values to a class.
104 And sometimes, certain attributes aren't even intended to be passed but you want to allow for customization anyways for easier testing.
105
106 This is when default values come into play:
107
108 ```{doctest}
109 >>> from attrs import Factory
110 >>> @define
111 ... class C:
112 ... a: int = 42
113 ... b: list = field(factory=list)
114 ... c: list = Factory(list) # syntactic sugar for above
115 ... d: dict = field()
116 ... @d.default
117 ... def _any_name_except_a_name_of_an_attribute(self):
118 ... return {}
119 >>> C()
120 C(a=42, b=[], c=[], d={})
121 ```
122
123 It's important that the decorated method -- or any other method or property! -- doesn't have the same name as the attribute, otherwise it would overwrite the attribute definition.
124
125 Please note that as with function and method signatures, `default=[]` will *not* do what you may think it might do:
126
127 ```{doctest}
128 >>> @define
129 ... class C:
130 ... x = []
131 >>> i = C()
132 >>> k = C()
133 >>> i.x.append(42)
134 >>> k.x
135 [42]
136 ```
137
138 This is why *attrs* comes with factory options.
139
140 :::{warning}
141 Please note that the decorator based defaults have one gotcha:
142 they are executed when the attribute is set, that means depending on the order of attributes, the `self` object may not be fully initialized when they're called.
143
144 Therefore you should use `self` as little as possible.
145
146 Even the smartest of us can [get confused](https://github.com/python-attrs/attrs/issues/289) by what happens if you pass partially initialized objects around.
147 :::
148
149 (validators)=
150
151 ## Validators
152
153 Another thing that definitely *does* belong in `__init__` is checking the resulting instance for invariants.
154 This is why *attrs* has the concept of validators.
155
156
157 ### Decorator
158
159 The most straightforward way is using the attribute's `validator` method as a decorator.
160
161 The method has to accept three arguments:
162
163 1. the *instance* that's being validated (aka `self`),
164 2. the *attribute* that it's validating, and finally
165 3. the *value* that is passed for it.
166
167 These values are passed as *positional arguments*, therefore their names don't matter.
168
169 If the value does not pass the validator's standards, it just raises an appropriate exception.
170
171 ```{doctest}
172 >>> @define
173 ... class C:
174 ... x: int = field()
175 ... @x.validator
176 ... def _check_x(self, attribute, value):
177 ... if value > 42:
178 ... raise ValueError("x must be smaller or equal to 42")
179 >>> C(42)
180 C(x=42)
181 >>> C(43)
182 Traceback (most recent call last):
183 ...
184 ValueError: x must be smaller or equal to 42
185 ```
186
187 Again, it's important that the decorated method doesn't have the same name as the attribute and that the {func}`attrs.field` helper is used.
188
189
190 ### Callables
191
192 If you want to re-use your validators, you should have a look at the `validator` argument to {func}`attrs.field`.
193
194 It takes either a callable or a list of callables (usually functions) and treats them as validators that receive the same arguments as with the decorator approach.
195 Also as with the decorator approach, they are passed as *positional arguments* so you can name them however you want.
196
197 Since the validators run *after* the instance is initialized, you can refer to other attributes while validating:
198
199 ```{doctest}
200 >>> import attrs
201 >>> def x_smaller_than_y(instance, attribute, value):
202 ... if value >= instance.y:
203 ... raise ValueError("'x' has to be smaller than 'y'!")
204 >>> @define
205 ... class C:
206 ... x = field(validator=[attrs.validators.instance_of(int),
207 ... x_smaller_than_y])
208 ... y = field()
209 >>> C(x=3, y=4)
210 C(x=3, y=4)
211 >>> C(x=4, y=3)
212 Traceback (most recent call last):
213 ...
214 ValueError: 'x' has to be smaller than 'y'!
215 ```
216
217 This example demonstrates a convenience shortcut:
218 Passing a list of validators directly is equivalent to passing them wrapped in the {obj}`attrs.validators.and_` validator and all validators must pass.
219
220 *attrs* won't intercept your changes to those attributes but you can always call {func}`attrs.validate` on any instance to verify that it's still valid:
221
222 When using {func}`attrs.define` or [`attrs.frozen`](attrs.frozen), however, *attrs* will run the validators even when setting the attribute.
223
224 ```{doctest}
225 >>> i = C(4, 5)
226 >>> i.x = 5
227 Traceback (most recent call last):
228 ...
229 ValueError: 'x' has to be smaller than 'y'!
230 ```
231
232 *attrs* ships with a bunch of validators, make sure to [check them out]( api-validators) before writing your own:
233
234 ```{doctest}
235 >>> @define
236 ... class C:
237 ... x = field(validator=attrs.validators.instance_of(int))
238 >>> C(42)
239 C(x=42)
240 >>> C("42")
241 Traceback (most recent call last):
242 ...
243 TypeError: ("'x' must be <type 'int'> (got '42' that is a <type 'str'>).", Attribute(name='x', default=NOTHING, factory=NOTHING, validator=<instance_of validator for type <type 'int'>>, type=None), <type 'int'>, '42')
244 ```
245
246 Of course you can mix and match the two approaches at your convenience.
247 If you use both ways to define validators for an attribute, they are both ran:
248
249 ```{doctest}
250 >>> @define
251 ... class C:
252 ... x = field(validator=attrs.validators.instance_of(int))
253 ... @x.validator
254 ... def fits_byte(self, attribute, value):
255 ... if not 0 <= value < 256:
256 ... raise ValueError("value out of bounds")
257 >>> C(128)
258 C(x=128)
259 >>> C("128")
260 Traceback (most recent call last):
261 ...
262 TypeError: ("'x' must be <class 'int'> (got '128' that is a <class 'str'>).", Attribute(name='x', default=NOTHING, validator=[<instance_of validator for type <class 'int'>>, <function fits_byte at 0x10fd7a0d0>], repr=True, cmp=True, hash=True, init=True, metadata=mappingproxy({}), type=None, converter=one), <class 'int'>, '128')
263 >>> C(256)
264 Traceback (most recent call last):
265 ...
266 ValueError: value out of bounds
267 ```
268
269 Finally, validators can be globally disabled:
270
271 ```{doctest}
272 >>> attrs.validators.set_disabled(True)
273 >>> C("128")
274 C(x='128')
275 >>> attrs.validators.set_disabled(False)
276 >>> C("128")
277 Traceback (most recent call last):
278 ...
279 TypeError: ("'x' must be <class 'int'> (got '128' that is a <class 'str'>).", Attribute(name='x', default=NOTHING, validator=[<instance_of validator for type <class 'int'>>, <function fits_byte at 0x10fd7a0d0>], repr=True, cmp=True, hash=True, init=True, metadata=mappingproxy({}), type=None, converter=None), <class 'int'>, '128')
280 ```
281
282 ... or within a context manager:
283
284 ```{doctest}
285 >>> with attrs.validators.disabled():
286 ... C("128")
287 C(x='128')
288 >>> C("128")
289 Traceback (most recent call last):
290 ...
291 TypeError: ("'x' must be <class 'int'> (got '128' that is a <class 'str'>).", Attribute(name='x', default=NOTHING, validator=[<instance_of validator for type <class 'int'>>, <function fits_byte at 0x10fd7a0d0>], repr=True, cmp=True, hash=True, init=True, metadata=mappingproxy({}), type=None, converter=None), <class 'int'>, '128')
292 ```
293
294 (converters)=
295
296 ## Converters
297
298 Sometimes, it is necessary to normalize the values coming in, therefore *attrs* comes with converters.
299
300 Attributes can have a `converter` function specified, which will be called with the attribute's passed-in value to get a new value to use.
301 This can be useful for doing type-conversions on values that you don't want to force your callers to do.
302
303 ```{doctest}
304 >>> @define
305 ... class C:
306 ... x = field(converter=int)
307 >>> o = C("1")
308 >>> o.x
309 1
310 >>> o.x = "2"
311 >>> o.x
312 2
313 ```
314
315 Converters are run *before* validators, so you can use validators to check the final form of the value.
316
317 ```{doctest}
318 >>> def validate_x(instance, attribute, value):
319 ... if value < 0:
320 ... raise ValueError("x must be at least 0.")
321 >>> @define
322 ... class C:
323 ... x = field(converter=int, validator=validate_x)
324 >>> o = C("0")
325 >>> o.x
326 0
327 >>> C("-1")
328 Traceback (most recent call last):
329 ...
330 ValueError: x must be at least 0.
331 ```
332
333 Arguably, you can abuse converters as one-argument validators:
334
335 ```{doctest}
336 >>> C("x")
337 Traceback (most recent call last):
338 ...
339 ValueError: invalid literal for int() with base 10: 'x'
340 ```
341
342 If a converter's first argument has a type annotation, that type will appear in the signature for `__init__`.
343 A converter will override an explicit type annotation or `type` argument.
344
345 ```{doctest}
346 >>> def str2int(x: str) -> int:
347 ... return int(x)
348 >>> @define
349 ... class C:
350 ... x = field(converter=str2int)
351 >>> C.__init__.__annotations__
352 {'return': None, 'x': <class 'str'>}
353 ```
354
355
356 ## Hooking Yourself Into Initialization
357
358 Generally speaking, the moment you realize the need of finer control – than what *attrs* offers – over how a class is instantiated, it's usually best to use a {obj}`classmethod` factory or to apply the [builder pattern](https://en.wikipedia.org/wiki/Builder_pattern).
359
360 However, sometimes you need to do that one quick thing before or after your class is initialized.
361 For that purpose, *attrs* offers the following options:
362
363 - `__attrs_pre_init__` is automatically detected and run *before* *attrs* starts initializing.
364 If `__attrs_pre_init__` takes more than the `self` argument, the *attrs*-generated `__init__` will call it with the same arguments it received itself.
365 This is useful if you need to inject a call to `super().__init__()` -- with or without arguments.
366
367 - `__attrs_post_init__` is automatically detected and run *after* *attrs* is done initializing your instance.
368 This is useful if you want to derive some attribute from others or perform some kind of validation over the whole instance.
369
370 - `__attrs_init__` is written and attached to your class *instead* of `__init__`, if *attrs* is told to not write one (i.e. `init=False` or a combination of `auto_detect=True` and a custom `__init__`).
371 This is useful if you want full control over the initialization process, but don't want to set the attributes by hand.
372
373
374 ### Pre Init
375
376 The sole reason for the existence of `__attrs_pre_init__` is to give users the chance to call `super().__init__()`, because some subclassing-based APIs require that.
377
378 ```{doctest}
379 >>> @define
380 ... class C:
381 ... x: int
382 ... def __attrs_pre_init__(self):
383 ... super().__init__()
384 >>> C(42)
385 C(x=42)
386 ```
387
388 If you need more control, use the custom init approach described next.
389
390
391 ### Custom Init
392
393 If you tell *attrs* to not write an `__init__`, it will write an `__attrs_init__` instead, with the same code that it would have used for `__init__`.
394 You have full control over the initialization, but also have to type out the types of your arguments etc.
395 Here's an example of a manual default value:
396
397 ```{doctest}
398 >>> @define
399 ... class C:
400 ... x: int
401 ...
402 ... def __init__(self, x: int = 42):
403 ... self.__attrs_init__(x)
404 >>> C()
405 C(x=42)
406 ```
407
408
409 ### Post Init
410
411 ```{doctest}
412 >>> @define
413 ... class C:
414 ... x: int
415 ... y: int = field(init=False)
416 ... def __attrs_post_init__(self):
417 ... self.y = self.x + 1
418 >>> C(1)
419 C(x=1, y=2)
420 ```
421
422 Please note that you can't directly set attributes on frozen classes:
423
424 ```{doctest}
425 >>> @frozen
426 ... class FrozenBroken:
427 ... x: int
428 ... y: int = field(init=False)
429 ... def __attrs_post_init__(self):
430 ... self.y = self.x + 1
431 >>> FrozenBroken(1)
432 Traceback (most recent call last):
433 ...
434 attrs.exceptions.FrozenInstanceError: can't set attribute
435 ```
436
437 If you need to set attributes on a frozen class, you'll have to resort to the [same trick](how-frozen) as *attrs* and use {meth}`object.__setattr__`:
438
439 ```{doctest}
440 >>> @define
441 ... class Frozen:
442 ... x: int
443 ... y: int = field(init=False)
444 ... def __attrs_post_init__(self):
445 ... object.__setattr__(self, "y", self.x + 1)
446 >>> Frozen(1)
447 Frozen(x=1, y=2)
448 ```
449
450 Note that you *must not* access the hash code of the object in `__attrs_post_init__` if `cache_hash=True`.
451
452
453 ## Order of Execution
454
455 If present, the hooks are executed in the following order:
456
457 1. `__attrs_pre_init__` (if present on *current* class)
458
459 2. For each attribute, in the order it was declared:
460
461 1. default factory
462 2. converter
463
464 3. *all* validators
465
466 4. `__attrs_post_init__` (if present on *current* class)
467
468 Notably this means, that you can access all attributes from within your validators, but your converters have to deal with invalid values and have to return a valid value.
469
470
471 ## Derived Attributes
472
473 One of the most common *attrs* questions on *Stack Overflow* is how to have attributes that depend on other attributes.
474 For example if you have an API token and want to instantiate a web client that uses it for authentication.
475 Based on the previous sections, there are two approaches.
476
477 The simpler one is using `__attrs_post_init__`:
478
479 ```python
480 @define
481 class APIClient:
482 token: str
483 client: WebClient = field(init=False)
484
485 def __attrs_post_init__(self):
486 self.client = WebClient(self.token)
487 ```
488
489 The second one is using a decorator-based default:
490
491 ```python
492 @define
493 class APIClient:
494 token: str
495 client: WebClient = field() # needed! attr.ib works too
496
497 @client.default
498 def _client_factory(self):
499 return WebClient(self.token)
500 ```
501
502 That said, and as pointed out in the beginning of the chapter, a better approach would be to have a factory class method:
503
504 ```python
505 @define
506 class APIClient:
507 client: WebClient
508
509 @classmethod
510 def from_token(cls, token: str) -> "APIClient":
511 return cls(client=WebClient(token))
512 ```
513
514 This makes the class more testable.