| 1 |
(how)= |
| 2 |
|
| 3 |
# How Does It Work? |
| 4 |
|
| 5 |
## Boilerplate |
| 6 |
|
| 7 |
*attrs* isn't the first library that aims to simplify class definition in Python. |
| 8 |
But its **declarative** approach combined with **no runtime overhead** lets it stand out. |
| 9 |
|
| 10 |
Once you apply the `@attrs.define` (or `@attr.s`) decorator to a class, *attrs* searches the class object for instances of `attr.ib`s. |
| 11 |
Internally they're a representation of the data passed into `attr.ib` along with a counter to preserve the order of the attributes. |
| 12 |
Alternatively, it's possible to define them using {doc}`types`. |
| 13 |
|
| 14 |
In order to ensure that subclassing works as you'd expect it to work, *attrs* also walks the class hierarchy and collects the attributes of all base classes. |
| 15 |
Please note that *attrs* does *not* call `super()` *ever*. |
| 16 |
It will write {term}`dunder methods` to work on *all* of those attributes which also has performance benefits due to fewer function calls. |
| 17 |
|
| 18 |
Once *attrs* knows what attributes it has to work on, it writes the requested {term}`dunder methods` and -- depending on whether you wish to have a {term}`dict <dict classes>` or {term}`slotted <slotted classes>` class -- creates a new class for you (`slots=True`) or attaches them to the original class (`slots=False`). |
| 19 |
While creating new classes is more elegant, we've run into several edge cases surrounding metaclasses that make it impossible to go this route unconditionally. |
| 20 |
|
| 21 |
To be very clear: if you define a class with a single attribute without a default value, the generated `__init__` will look *exactly* how you'd expect: |
| 22 |
|
| 23 |
```{doctest} |
| 24 |
>>> import inspect |
| 25 |
>>> from attrs import define |
| 26 |
>>> @define |
| 27 |
... class C: |
| 28 |
... x: int |
| 29 |
>>> print(inspect.getsource(C.__init__)) |
| 30 |
def __init__(self, x): |
| 31 |
self.x = x |
| 32 |
<BLANKLINE> |
| 33 |
``` |
| 34 |
|
| 35 |
No magic, no meta programming, no expensive introspection at runtime. |
| 36 |
|
| 37 |
--- |
| 38 |
|
| 39 |
Everything until this point happens exactly *once* when the class is defined. |
| 40 |
As soon as a class is done, it's done. |
| 41 |
And it's just a regular Python class like any other, except for a single `__attrs_attrs__` attribute that *attrs* uses internally. |
| 42 |
Much of the information is accessible via {func}`attrs.fields` and other functions which can be used for introspection or for writing your own tools and decorators on top of *attrs* (like {func}`attrs.asdict`). |
| 43 |
|
| 44 |
And once you start instantiating your classes, *attrs* is out of your way completely. |
| 45 |
|
| 46 |
This **static** approach was very much a design goal of *attrs* and what I strongly believe makes it distinct. |
| 47 |
|
| 48 |
(how-frozen)= |
| 49 |
|
| 50 |
## Immutability |
| 51 |
|
| 52 |
In order to give you immutability, *attrs* will attach a `__setattr__` method to your class that raises an {class}`attrs.exceptions.FrozenInstanceError` whenever anyone tries to set an attribute. |
| 53 |
|
| 54 |
The same is true if you choose to freeze individual attributes using the {obj}`attrs.setters.frozen` *on_setattr* hook -- except that the exception becomes {class}`attrs.exceptions.FrozenAttributeError`. |
| 55 |
|
| 56 |
Both exceptions subclass {class}`attrs.exceptions.FrozenError`. |
| 57 |
|
| 58 |
--- |
| 59 |
|
| 60 |
Depending on whether a class is a dict class or a slotted class, *attrs* uses a different technique to circumvent that limitation in the `__init__` method. |
| 61 |
|
| 62 |
Once constructed, frozen instances don't differ in any way from regular ones except that you cannot change its attributes. |
| 63 |
|
| 64 |
### Dict Classes |
| 65 |
|
| 66 |
Dict classes -- i.e. regular classes -- simply assign the value directly into the class' eponymous `__dict__` (and there's nothing we can do to stop the user to do the same). |
| 67 |
|
| 68 |
The performance impact is negligible. |
| 69 |
|
| 70 |
### Slotted Classes |
| 71 |
|
| 72 |
Slotted classes are more complicated. |
| 73 |
Here it uses (an aggressively cached) {meth}`object.__setattr__` to set your attributes. |
| 74 |
This is (still) slower than a plain assignment: |
| 75 |
|
| 76 |
```none |
| 77 |
$ pyperf timeit --rigorous \ |
| 78 |
-s "import attr; C = attr.make_class('C', ['x', 'y', 'z'], slots=True)" \ |
| 79 |
"C(1, 2, 3)" |
| 80 |
......................................... |
| 81 |
Mean +- std dev: 228 ns +- 18 ns |
| 82 |
|
| 83 |
$ pyperf timeit --rigorous \ |
| 84 |
-s "import attr; C = attr.make_class('C', ['x', 'y', 'z'], slots=True, frozen=True)" \ |
| 85 |
"C(1, 2, 3)" |
| 86 |
......................................... |
| 87 |
Mean +- std dev: 425 ns +- 16 ns |
| 88 |
``` |
| 89 |
|
| 90 |
So on a laptop computer the difference is about 200 nanoseconds (1 second is 1,000,000,000 nanoseconds). |
| 91 |
It's certainly something you'll feel in a hot loop but shouldn't matter in normal code. |
| 92 |
Pick what's more important to you. |
| 93 |
|
| 94 |
### Summary |
| 95 |
|
| 96 |
You should avoid instantiating lots of frozen slotted classes (i.e. `@frozen`) in performance-critical code. |
| 97 |
|
| 98 |
Frozen dict classes have barely a performance impact, unfrozen slotted classes are even *faster* than unfrozen dict classes (i.e. regular classes). |
| 99 |
|
| 100 |
|
| 101 |
(how-slotted-cached_property)= |
| 102 |
|
| 103 |
## Cached Properties on Slotted Classes. |
| 104 |
|
| 105 |
By default, the standard library `functools.cached_property` decorator does not work on slotted classes, |
| 106 |
because it requires a `__dict__` to store the cached value. |
| 107 |
This could be surprising when uses *attrs*, as makes using slotted classes so easy, |
| 108 |
so attrs will convert `functools.cached_property` decorated methods, when constructing slotted classes. |
| 109 |
|
| 110 |
Getting this working is achieved by: |
| 111 |
* Adding names to `__slots__` for the wrapped methods. |
| 112 |
* Adding a `__getattr__` method to set values on the wrapped methods. |
| 113 |
|
| 114 |
For most users this should mean that it works transparently. |
| 115 |
|
| 116 |
Note that the implementation does not guarantee that the wrapped method is called |
| 117 |
only once in multi-threaded usage. This matches the implementation of `cached_property` |
| 118 |
in python v3.12. |