Debian Codegraph @

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

raw
1 # *attrs* by Example
2
3 ## Basics
4
5 The simplest possible usage is:
6
7 ```{doctest}
8 >>> from attrs import define, field
9 >>> @define
10 ... class Empty:
11 ... pass
12 >>> Empty()
13 Empty()
14 >>> Empty() == Empty()
15 True
16 >>> Empty() is Empty()
17 False
18 ```
19
20 So in other words: *attrs* is useful even without actual attributes!
21
22 But you'll usually want some data on your classes, so let's add some:
23
24 ```{doctest}
25 >>> @define
26 ... class Coordinates:
27 ... x: int
28 ... y: int
29 ```
30
31 By default, all features are added, so you immediately have a fully functional data class with a nice `repr` string and comparison methods.
32
33 ```{doctest}
34 >>> c1 = Coordinates(1, 2)
35 >>> c1
36 Coordinates(x=1, y=2)
37 >>> c2 = Coordinates(x=2, y=1)
38 >>> c2
39 Coordinates(x=2, y=1)
40 >>> c1 == c2
41 False
42 ```
43
44 As shown, the generated `__init__` method allows for both positional and keyword arguments.
45
46 ---
47
48 Unlike Data Classes, *attrs* doesn't force you to use type annotations.
49 So, the previous example could also have been written as:
50
51 ```{doctest}
52 >>> @define
53 ... class Coordinates:
54 ... x = field()
55 ... y = field()
56 >>> Coordinates(1, 2)
57 Coordinates(x=1, y=2)
58 ```
59
60 :::{caution}
61 If a class body contains a field that is defined using {func}`attrs.field` (or {func}`attr.ib`), but **lacks a type annotation**, *attrs* switches to a no-typing mode and ignores fields that have type annotations but are not defined using {func}`attrs.field` (or {func}`attr.ib`).
62 :::
63
64 ---
65
66 For private attributes, *attrs* will strip the leading underscores for keyword arguments:
67
68 ```{doctest}
69 >>> @define
70 ... class C:
71 ... _x: int
72 >>> C(x=1)
73 C(_x=1)
74 ```
75
76 If you want to initialize your private attributes yourself, you can do that too:
77
78 ```{doctest}
79 >>> @define
80 ... class C:
81 ... _x: int = field(init=False, default=42)
82 >>> C()
83 C(_x=42)
84 >>> C(23)
85 Traceback (most recent call last):
86 ...
87 TypeError: __init__() takes exactly 1 argument (2 given)
88 ```
89
90 If you prefer to expose your privates, you can use keyword argument aliases:
91
92 ```{doctest}
93 >>> @define
94 ... class C:
95 ... _x: int = field(alias="_x")
96 >>> C(_x=1)
97 C(_x=1)
98 ```
99
100 An additional way of defining attributes is supported too.
101 This is useful in times when you want to enhance classes that are not yours (nice `__repr__` for Django models anyone?):
102
103 ```{doctest}
104 >>> class SomethingFromSomeoneElse:
105 ... def __init__(self, x):
106 ... self.x = x
107 >>> SomethingFromSomeoneElse = define(
108 ... these={
109 ... "x": field()
110 ... }, init=False)(SomethingFromSomeoneElse)
111 >>> SomethingFromSomeoneElse(1)
112 SomethingFromSomeoneElse(x=1)
113 ```
114
115 [Subclassing is bad for you](https://www.youtube.com/watch?v=3MNVP9-hglc), but *attrs* will still do what you'd hope for:
116
117 ```{doctest}
118 >>> @define(slots=False)
119 ... class A:
120 ... a: int
121 ... def get_a(self):
122 ... return self.a
123 >>> @define(slots=False)
124 ... class B:
125 ... b: int
126 >>> @define(slots=False)
127 ... class C(B, A):
128 ... c: int
129 >>> i = C(1, 2, 3)
130 >>> i
131 C(a=1, b=2, c=3)
132 >>> i == C(1, 2, 3)
133 True
134 >>> i.get_a()
135 1
136 ```
137
138 {term}`Slotted classes <slotted classes>`, which are the default for the new APIs, don't play well with multiple inheritance so we don't use them in the example.
139
140 The order of the attributes is defined by the [MRO](https://www.python.org/download/releases/2.3/mro/).
141
142
143 ### Keyword-only Attributes
144
145 You can also add [keyword-only](https://docs.python.org/3/glossary.html#keyword-only-parameter) attributes:
146
147 ```{doctest}
148 >>> @define
149 ... class A:
150 ... a: int = field(kw_only=True)
151 >>> A()
152 Traceback (most recent call last):
153 ...
154 TypeError: A() missing 1 required keyword-only argument: 'a'
155 >>> A(a=1)
156 A(a=1)
157 ```
158
159 `kw_only` may also be specified at decorator level, and will apply to all attributes:
160
161 ```{doctest}
162 >>> @define(kw_only=True)
163 ... class A:
164 ... a: int
165 ... b: int
166 >>> A(1, 2)
167 Traceback (most recent call last):
168 ...
169 TypeError: __init__() takes 1 positional argument but 3 were given
170 >>> A(a=1, b=2)
171 A(a=1, b=2)
172 ```
173
174 If you create an attribute with `init=False`, the `kw_only` argument is ignored.
175
176 Keyword-only attributes allow subclasses to add attributes without default values, even if the base class defines attributes with default values:
177
178 ```{doctest}
179 >>> @define
180 ... class A:
181 ... a: int = 0
182 >>> @define
183 ... class B(A):
184 ... b: int = field(kw_only=True)
185 >>> B(b=1)
186 B(a=0, b=1)
187 >>> B()
188 Traceback (most recent call last):
189 ...
190 TypeError: B() missing 1 required keyword-only argument: 'b'
191 ```
192
193 If you don't set `kw_only=True`, then there is no valid attribute ordering, and you'll get an error:
194
195 ```{doctest}
196 >>> @define
197 ... class A:
198 ... a: int = 0
199 >>> @define
200 ... class B(A):
201 ... b: int
202 Traceback (most recent call last):
203 ...
204 ValueError: No mandatory attributes allowed after an attribute with a default value or factory. Attribute in question: Attribute(name='b', default=NOTHING, validator=None, repr=True, cmp=True, hash=None, init=True, converter=None, metadata=mappingproxy({}), type=int, kw_only=False)
205 ```
206
207 (asdict)=
208
209 ## Converting to Collections Types
210
211 When you have a class with data, it often is very convenient to transform that class into a {class}`dict` (for example if you want to serialize it to JSON):
212
213 ```{doctest}
214 >>> from attrs import asdict
215 >>> asdict(Coordinates(x=1, y=2))
216 {'x': 1, 'y': 2}
217 ```
218
219 Some fields cannot or should not be transformed.
220 For that, {func}`attrs.asdict` offers a callback that decides whether an attribute should be included:
221
222 ```{doctest}
223 >>> @define
224 ... class User:
225 ... email: str
226 ... password: str
227
228 >>> @define
229 ... class UserList:
230 ... users: list[User]
231
232 >>> asdict(UserList([User("[email protected]", "s33kred"),
233 ... User("[email protected]", "p4ssw0rd")]),
234 ... filter=lambda attr, value: attr.name != "password")
235 {'users': [{'email': '[email protected]'}, {'email': '[email protected]'}]}
236 ```
237
238 For the common case where you want to [`include`](attrs.filters.include) or [`exclude`](attrs.filters.exclude) certain types, string name or attributes, *attrs* ships with a few helpers:
239
240 ```{doctest}
241 >>> from attrs import asdict, filters, fields
242
243 >>> @define
244 ... class User:
245 ... login: str
246 ... password: str
247 ... email: str
248 ... id: int
249
250 >>> asdict(
251 ... User("jane", "s33kred", "[email protected]", 42),
252 ... filter=filters.exclude(fields(User).password, "email", int))
253 {'login': 'jane'}
254
255 >>> @define
256 ... class C:
257 ... x: str
258 ... y: str
259 ... z: int
260
261 >>> asdict(C("foo", "2", 3),
262 ... filter=filters.include(int, fields(C).x))
263 {'x': 'foo', 'z': 3}
264
265 >>> asdict(C("foo", "2", 3),
266 ... filter=filters.include(fields(C).x, "z"))
267 {'x': 'foo', 'z': 3}
268 ```
269
270 :::{note}
271 Though using string names directly is convenient, mistyping attribute names will silently do the wrong thing and neither Python nor your type checker can help you.
272 {func}`attrs.fields()` will raise an `AttributeError` when the field doesn't exist while literal string names won't.
273 Using {func}`attrs.fields()` to get attributes is worth being recommended in most cases.
274
275 ```{doctest}
276 >>> asdict(
277 ... User("jane", "s33kred", "[email protected]", 42),
278 ... filter=filters.exclude("passwd")
279 ... )
280 {'login': 'jane', 'password': 's33kred', 'email': '[email protected]', 'id': 42}
281
282 >>> asdict(
283 ... User("jane", "s33kred", "[email protected]", 42),
284 ... filter=fields(User).passwd
285 ... )
286 Traceback (most recent call last):
287 ...
288 AttributeError: 'UserAttributes' object has no attribute 'passwd'. Did you mean: 'password'?
289 ```
290 :::
291
292 Other times, all you want is a tuple and *attrs* won't let you down:
293
294 ```{doctest}
295 >>> import sqlite3
296 >>> from attrs import astuple
297
298 >>> @define
299 ... class Foo:
300 ... a: int
301 ... b: int
302
303 >>> foo = Foo(2, 3)
304 >>> with sqlite3.connect(":memory:") as conn:
305 ... c = conn.cursor()
306 ... c.execute("CREATE TABLE foo (x INTEGER PRIMARY KEY ASC, y)") #doctest: +ELLIPSIS
307 ... c.execute("INSERT INTO foo VALUES (?, ?)", astuple(foo)) #doctest: +ELLIPSIS
308 ... foo2 = Foo(*c.execute("SELECT x, y FROM foo").fetchone())
309 <sqlite3.Cursor object at ...>
310 <sqlite3.Cursor object at ...>
311 >>> foo == foo2
312 True
313 ```
314
315 For more advanced transformations and conversions, we recommend you look at a companion library (such as [*cattrs*](https://catt.rs/)).
316
317
318 ## Defaults
319
320 Sometimes you want to have default values for your initializer.
321 And sometimes you even want mutable objects as default values (ever accidentally used `def f(arg=[])`?).
322 *attrs* has you covered in both cases:
323
324 ```{doctest}
325 >>> import collections
326
327 >>> @define
328 ... class Connection:
329 ... socket: int
330 ... @classmethod
331 ... def connect(cls, db_string):
332 ... # ... connect somehow to db_string ...
333 ... return cls(socket=42)
334
335 >>> @define
336 ... class ConnectionPool:
337 ... db_string: str
338 ... pool: collections.deque = Factory(collections.deque)
339 ... debug: bool = False
340 ... def get_connection(self):
341 ... try:
342 ... return self.pool.pop()
343 ... except IndexError:
344 ... if self.debug:
345 ... print("New connection!")
346 ... return Connection.connect(self.db_string)
347 ... def free_connection(self, conn):
348 ... if self.debug:
349 ... print("Connection returned!")
350 ... self.pool.appendleft(conn)
351 ...
352 >>> cp = ConnectionPool("postgres://localhost")
353 >>> cp
354 ConnectionPool(db_string='postgres://localhost', pool=deque([]), debug=False)
355 >>> conn = cp.get_connection()
356 >>> conn
357 Connection(socket=42)
358 >>> cp.free_connection(conn)
359 >>> cp
360 ConnectionPool(db_string='postgres://localhost', pool=deque([Connection(socket=42)]), debug=False)
361 ```
362
363 More information on why class methods for constructing objects are awesome can be found in this insightful [blog post](https://web.archive.org/web/20210130220433/http://as.ynchrono.us/2014/12/asynchronous-object-initialization.html).
364
365 Default factories can also be set using the `factory` argument to {func}`~attrs.field`, and using a decorator.
366 The method receives the partially initialized instance which enables you to base a default value on other attributes:
367
368 ```{doctest}
369 >>> @define
370 ... class C:
371 ... x: int = 1
372 ... y: int = field()
373 ... @y.default
374 ... def _any_name_except_a_name_of_an_attribute(self):
375 ... return self.x + 1
376 ... z: list = field(factory=list)
377 >>> C()
378 C(x=1, y=2, z=[])
379 ```
380
381 Please keep in mind that the decorator approach *only* works if the attribute in question has a {func}`~attrs.field` assigned to it.
382 As a result, annotating an attribute with a type is *not* enough if you use `@default`.
383
384 (examples-validators)=
385
386 ## Validators
387
388 Although your initializers should do as little as possible (ideally: just initialize your instance according to the arguments!), it can come in handy to do some kind of validation on the arguments.
389
390 *attrs* offers two ways to define validators for each attribute and it's up to you to choose which one suits your style and project better.
391
392 You can use a decorator:
393
394 ```{doctest}
395 >>> @define
396 ... class C:
397 ... x: int = field()
398 ... @x.validator
399 ... def check(self, attribute, value):
400 ... if value > 42:
401 ... raise ValueError("x must be smaller or equal to 42")
402 >>> C(42)
403 C(x=42)
404 >>> C(43)
405 Traceback (most recent call last):
406 ...
407 ValueError: x must be smaller or equal to 42
408 ```
409
410 ...or a callable...
411
412 ```{doctest}
413 >>> from attrs import validators
414
415 >>> def x_smaller_than_y(instance, attribute, value):
416 ... if value >= instance.y:
417 ... raise ValueError("'x' has to be smaller than 'y'!")
418 >>> @define
419 ... class C:
420 ... x: int = field(validator=[validators.instance_of(int),
421 ... x_smaller_than_y])
422 ... y: int
423 >>> C(x=3, y=4)
424 C(x=3, y=4)
425 >>> C(x=4, y=3)
426 Traceback (most recent call last):
427 ...
428 ValueError: 'x' has to be smaller than 'y'!
429 ```
430
431 ...or both at once:
432
433 ```{doctest}
434 >>> @define
435 ... class C:
436 ... x: int = field(validator=validators.instance_of(int))
437 ... @x.validator
438 ... def fits_byte(self, attribute, value):
439 ... if not 0 <= value < 256:
440 ... raise ValueError("value out of bounds")
441 >>> C(128)
442 C(x=128)
443 >>> C("128")
444 Traceback (most recent call last):
445 ...
446 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=int, converter=None, kw_only=False), <class 'int'>, '128')
447 >>> C(256)
448 Traceback (most recent call last):
449 ...
450 ValueError: value out of bounds
451 ```
452
453 Please note that the decorator approach only works if -- and only if! -- the attribute in question has a {func}`~attrs.field` assigned.
454 Therefore if you use `@validator`, it is *not* enough to annotate said attribute with a type.
455
456 *attrs* ships with a bunch of validators, make sure to [check them out](api-validators) before writing your own:
457
458 ```{doctest}
459 >>> @define
460 ... class C:
461 ... x: int = field(validator=validators.instance_of(int))
462 >>> C(42)
463 C(x=42)
464 >>> C("42")
465 Traceback (most recent call last):
466 ...
467 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, kw_only=False), <type 'int'>, '42')
468 ```
469
470 If using the old-school {func}`attr.s` decorator, validators only run on initialization by default.
471 If using the newer {func}`attrs.define` and friends, validators run on initialization *and* on attribute setting.
472 This behavior can be changed using the *on_setattr* argument.
473
474 Check out {ref}`validators` for more details.
475
476
477 ## Conversion
478
479 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.
480 This can be useful for doing type-conversions on values that you don't want to force your callers to do.
481
482 ```{doctest}
483 >>> @define
484 ... class C:
485 ... x: int = field(converter=int)
486 >>> o = C("1")
487 >>> o.x
488 1
489 >>> o.x = "2"
490 >>> o.x
491 2
492 ```
493
494 If using the old-school {func}`attr.s` decorator, converters only run on initialization by default.
495 If using the newer {func}`attrs.define` and friends, converters run on initialization *and* on attribute setting.
496 This behavior can be changed using the *on_setattr* argument.
497
498 Check out {ref}`converters` for more details.
499
500 (metadata)=
501
502 ## Metadata
503
504 All *attrs* attributes may include arbitrary metadata in the form of a read-only dictionary.
505
506 ```{doctest}
507 >>> from attrs import fields
508
509 >>> @define
510 ... class C:
511 ... x = field(metadata={'my_metadata': 1})
512 >>> fields(C).x.metadata
513 mappingproxy({'my_metadata': 1})
514 >>> fields(C).x.metadata['my_metadata']
515 1
516 ```
517
518 Metadata is not used by *attrs*, and is meant to enable rich functionality in third-party libraries.
519 The metadata dictionary follows the normal dictionary rules:
520 Keys need to be hashable, and both keys and values are recommended to be immutable.
521
522 If you're the author of a third-party library with *attrs* integration, please see [*Extending Metadata*](extending-metadata).
523
524
525 ## Types
526
527 *attrs* also allows you to associate a type with an attribute using either the *type* argument to using {pep}`526`-annotations or {func}`attrs.field`/{func}`attr.ib`:
528
529 ```{doctest}
530 >>> @define
531 ... class C:
532 ... x: int
533 >>> fields(C).x.type
534 <class 'int'>
535
536 >>> import attr
537 >>> @attr.s
538 ... class C:
539 ... x = attr.ib(type=int)
540 >>> fields(C).x.type
541 <class 'int'>
542 ```
543
544 If you don't mind annotating *all* attributes, you can even drop the `attrs.field` and assign default values instead:
545
546 ```{doctest}
547 >>> import typing
548
549 >>> @define
550 ... class AutoC:
551 ... cls_var: typing.ClassVar[int] = 5 # this one is ignored
552 ... l: list[int] = Factory(list)
553 ... x: int = 1
554 ... foo: str = "every attrib needs a type if auto_attribs=True"
555 ... bar: typing.Any = None
556 >>> fields(AutoC).l.type
557 list[int]
558 >>> fields(AutoC).x.type
559 <class 'int'>
560 >>> fields(AutoC).foo.type
561 <class 'str'>
562 >>> fields(AutoC).bar.type
563 typing.Any
564 >>> AutoC()
565 AutoC(l=[], x=1, foo='every attrib needs a type if auto_attribs=True', bar=None)
566 >>> AutoC.cls_var
567 5
568 ```
569
570 The generated `__init__` method will have an attribute called `__annotations__` that contains this type information.
571
572 If your annotations contain strings (e.g. forward references),
573 you can resolve these after all references have been defined by using {func}`attrs.resolve_types`.
574 This will replace the *type* attribute in the respective fields.
575
576 ```{doctest}
577 >>> from attrs import resolve_types
578
579 >>> @define
580 ... class A:
581 ... a: 'list[A]'
582 ... b: 'B'
583 ...
584 >>> @define
585 ... class B:
586 ... a: A
587 ...
588 >>> fields(A).a.type
589 'list[A]'
590 >>> fields(A).b.type
591 'B'
592 >>> resolve_types(A, globals(), locals())
593 <class 'A'>
594 >>> fields(A).a.type
595 list[A]
596 >>> fields(A).b.type
597 <class 'B'>
598 ```
599
600 :::{note}
601 If you find yourself using string type annotations to handle forward references, wrap the entire type annotation in quotes instead of only the type you need a forward reference to (so `'list[A]'` instead of `list['A']`).
602 This is a limitation of the Python typing system.
603 :::
604
605 :::{warning}
606 *attrs* itself doesn't have any features that work on top of type metadata.
607 However it's useful for writing your own validators or serialization frameworks.
608 :::
609
610
611 ## Slots
612
613 {term}`Slotted classes <slotted classes>` have several advantages on CPython.
614 Defining `__slots__` by hand is tedious, in *attrs* it's just a matter of using {func}`attrs.define` or passing `slots=True` to {func}`attr.s`:
615
616 ```{doctest}
617 >>> @define
618 ... class Coordinates:
619 ... x: int
620 ... y: int
621
622 >>> import attr
623
624 >>> @attr.s(slots=True)
625 ... class Coordinates:
626 ... x: int
627 ... y: int
628 ```
629
630 {func}`~attrs.define` sets `slots=True` by default.
631
632
633 ## Immutability
634
635 Sometimes you have instances that shouldn't be changed after instantiation.
636 Immutability is especially popular in functional programming and is generally a very good thing.
637 If you'd like to enforce it, *attrs* will try to help:
638
639 ```{doctest}
640 >>> from attrs import frozen
641
642 >>> @frozen
643 ... class C:
644 ... x: int
645 >>> i = C(1)
646 >>> i.x = 2
647 Traceback (most recent call last):
648 ...
649 attrs.exceptions.FrozenInstanceError: can't set attribute
650 >>> i.x
651 1
652 ```
653
654 Please note that true immutability is impossible in Python but it will [get](how-frozen) you 99% there.
655 By themselves, immutable classes are useful for long-lived objects that should never change; like configurations for example.
656
657 In order to use them in regular program flow, you'll need a way to easily create new instances with changed attributes.
658 In Clojure that function is called [*assoc*](https://clojuredocs.org/clojure.core/assoc) and *attrs* shamelessly imitates it: {func}`attrs.evolve`:
659
660 ```{doctest}
661 >>> from attrs import evolve, frozen
662
663 >>> @frozen
664 ... class C:
665 ... x: int
666 ... y: int
667 >>> i1 = C(1, 2)
668 >>> i1
669 C(x=1, y=2)
670 >>> i2 = evolve(i1, y=3)
671 >>> i2
672 C(x=1, y=3)
673 >>> i1 == i2
674 False
675 ```
676
677
678 ## Other Goodies
679
680 Sometimes you may want to create a class programmatically.
681 *attrs* gives you {func}`attrs.make_class` for that:
682
683 ```{doctest}
684 >>> from attrs import make_class
685 >>> @define
686 ... class C1:
687 ... x = field(type=int)
688 ... y = field()
689 >>> C2 = make_class("C2", {"x": field(type=int), "y": field()})
690 >>> fields(C1) == fields(C2)
691 True
692 >>> fields(C1).x.type
693 <class 'int'>
694 ```
695
696 You can still have power over the attributes if you pass a dictionary of name: {func}`~attrs.field` mappings and can pass the same arguments as you can to `@attrs.define`:
697
698 ```{doctest}
699 >>> C = make_class("C", {"x": field(default=42),
700 ... "y": field(default=Factory(list))},
701 ... repr=False)
702 >>> i = C()
703 >>> i # no repr added!
704 <__main__.C object at ...>
705 >>> i.x
706 42
707 >>> i.y
708 []
709 ```
710
711 If you need to dynamically make a class with {func}`~attrs.make_class` and it needs to be a subclass of something else than {class}`object`, use the `bases` argument:
712
713 ```{doctest}
714 >>> class D:
715 ... def __eq__(self, other):
716 ... return True # arbitrary example
717 >>> C = make_class("C", {}, bases=(D,), cmp=False)
718 >>> isinstance(C(), D)
719 True
720 ```
721
722 Sometimes, you want to have your class's `__init__` method do more than just
723 the initialization, validation, etc. that gets done for you automatically when
724 using `@define`.
725 To do this, just define a `__attrs_post_init__` method in your class.
726 It will get called at the end of the generated `__init__` method.
727
728 ```{doctest}
729 >>> @define
730 ... class C:
731 ... x: int
732 ... y: int
733 ... z: int = field(init=False)
734 ...
735 ... def __attrs_post_init__(self):
736 ... self.z = self.x + self.y
737 >>> obj = C(x=1, y=2)
738 >>> obj
739 C(x=1, y=2, z=3)
740 ```
741
742 You can exclude single attributes from certain methods:
743
744 ```{doctest}
745 >>> @define
746 ... class C:
747 ... user: str
748 ... password: str = field(repr=False)
749 >>> C("me", "s3kr3t")
750 C(user='me')
751 ```
752
753 Alternatively, to influence how the generated `__repr__()` method formats a specific attribute, specify a custom callable to be used instead of the `repr()` built-in function:
754
755 ```{doctest}
756 >>> @define
757 ... class C:
758 ... user: str
759 ... password: str = field(repr=lambda value: '***')
760 >>> C("me", "s3kr3t")
761 C(user='me', password=***)
762 ```