Debian Codegraph @

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

raw
1 # Why not…
2
3 If you'd like third party's account why *attrs* is great, have a look at Glyph's [*The One Python Library Everyone Needs*](https://glyph.twistedmatrix.com/2016/08/attrs.html).
4 It predates type annotations and hence Data Classes, but it masterfully illustrates the appeal of class-building packages.
5
6
7 ## … Data Classes?
8
9 {pep}`557` added Data Classes to [Python 3.7](https://docs.python.org/3.7/whatsnew/3.7.html#dataclasses) that resemble *attrs* in many ways.
10
11 They are the result of the Python community's [wish](https://mail.python.org/pipermail/python-ideas/2017-May/045618.html) to have an easier way to write classes in the standard library that doesn't carry the problems of `namedtuple`s.
12 To that end, *attrs* and its developers were involved in the PEP process and while we may disagree with some minor decisions that have been made, it's a fine library and if it stops you from abusing `namedtuple`s, they are a huge win.
13
14 Nevertheless, there are still reasons to prefer *attrs* over Data Classes.
15 Whether they're relevant to *you* depends on your circumstances:
16
17 - Data Classes are *intentionally* less powerful than *attrs*.
18 There is a long list of features that were sacrificed for the sake of simplicity and while the most obvious ones are validators, converters, {ref}`equality customization <custom-comparison>`, or {doc}`extensibility <extending>` in general, it permeates throughout all APIs.
19
20 On the other hand, Data Classes currently do not offer any significant feature that *attrs* doesn't already have.
21
22 - *attrs* supports all mainstream Python versions including PyPy.
23
24 - *attrs* doesn't force type annotations on you if you don't like them.
25
26 - But since it **also** supports typing, it's the best way to embrace type hints *gradually*, too.
27
28 - While Data Classes are implementing features from *attrs* every now and then, their presence is dependent on the Python version, not the package version.
29 For example, support for `__slots__` has only been added in Python 3.10, but it doesn’t do cell rewriting and therefore doesn’t support bare calls to `super()`.
30 This may or may not be fixed in later Python releases, but handling all these differences is especially painful for PyPI packages that support multiple Python versions.
31 And of course, this includes possible implementation bugs.
32
33 - *attrs* can and will move faster.
34 We are not bound to any release schedules and we have a clear deprecation policy.
35
36 One of the [reasons](https://peps.python.org/pep-0557/#why-not-just-use-attrs) to not vendor *attrs* in the standard library was to not impede *attrs*'s future development.
37
38 One way to think about *attrs* vs Data Classes is that *attrs* is a fully-fledged toolkit to write powerful classes while Data Classes are an easy way to get a class with some attributes.
39 Basically what *attrs* was in 2015.
40
41
42 ## … Pydantic?
43
44 Pydantic is first and foremost a *data validation & type coercion library*.
45 As such, it is a capable complement to class building libraries like *attrs* (or Data Classes!) for parsing and validating untrusted data.
46
47 However, as convenient as it might be, using it for your business or data layer [is problematic in several ways](https://threeofwands.com/why-i-use-attrs-instead-of-pydantic/):
48 Is it really necessary to re-validate all your objects while reading them from a trusted database?
49 In the parlance of [*Form, Command, and Model Validation*](https://verraes.net/2015/02/form-command-model-validation/), Pydantic is the right tool for *Commands*.
50
51 [*Separation of concerns*](https://en.wikipedia.org/wiki/Separation_of_concerns) feels tedious at times, but it's one of those things that you get to appreciate once you've shot your own foot often enough.
52
53 *attrs* emphatically does **not** try to be a validation library, but a toolkit to write well-behaved classes like you would write yourself.
54 If you'd like a powerful library for structuring, unstructuring, and validating data, have a look at [*cattrs*](https://catt.rs/) which is an official member of the *attrs* family.
55
56
57 ## … namedtuples?
58
59 {obj}`collections.namedtuple`s are tuples with names, not classes.[^history]
60 Since writing classes is tiresome in Python, every now and then someone discovers all the typing they could save and gets really excited.
61 However, that convenience comes at a price.
62
63 The most obvious difference between `namedtuple`s and *attrs*-based classes is that the latter are type-sensitive:
64
65 ```{doctest}
66 >>> import attrs
67 >>> C1 = attrs.make_class("C1", ["a"])
68 >>> C2 = attrs.make_class("C2", ["a"])
69 >>> i1 = C1(1)
70 >>> i2 = C2(1)
71 >>> i1.a == i2.a
72 True
73 >>> i1 == i2
74 False
75 ```
76
77 …while a `namedtuple` is *intentionally* [behaving like a tuple](https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences) which means the type of a tuple is *ignored*:
78
79 ```{doctest}
80 >>> from collections import namedtuple
81 >>> NT1 = namedtuple("NT1", "a")
82 >>> NT2 = namedtuple("NT2", "b")
83 >>> t1 = NT1(1)
84 >>> t2 = NT2(1)
85 >>> t1 == t2 == (1,)
86 True
87 ```
88
89 Other often surprising behaviors include:
90
91 - Since they are a subclass of tuples, `namedtuple`s have a length and are both iterable and indexable.
92 That's not what you'd expect from a class and is likely to shadow subtle typo bugs.
93
94 - Iterability also implies that it's easy to accidentally unpack a `namedtuple` which leads to hard-to-find bugs.[^iter]
95
96 - `namedtuple`s have their methods *on your instances* whether you like it or not.[^pollution]
97
98 - `namedtuple`s are *always* immutable.
99 Not only does that mean that you can't decide for yourself whether your instances should be immutable or not, it also means that if you want to influence your class' initialization (validation? default values?), you have to implement {meth}`__new__() <object.__new__>` which is a particularly hacky and error-prone requirement for a very common problem.[^immutable]
100
101 - To attach methods to a `namedtuple` you have to subclass it.
102 And if you follow the standard library documentation's recommendation of:
103
104 ```
105 class Point(namedtuple('Point', ['x', 'y'])):
106 # ...
107 ```
108
109 you end up with a class that has *two* `Point`s in its {attr}`__mro__ <class.__mro__>`: `[<class 'point.Point'>, <class 'point.Point'>, <type 'tuple'>, <type 'object'>]`.
110
111 That's not only confusing, it also has very practical consequences:
112 for example if you create documentation that includes class hierarchies like [*Sphinx*'s autodoc](https://www.sphinx-doc.org/en/stable/usage/extensions/autodoc.html) with `show-inheritance`.
113 Again: common problem, hacky solution with confusing fallout.
114
115 All these things make `namedtuple`s a particularly poor choice for public APIs because all your objects are irrevocably tainted.
116 With *attrs* your users won't notice a difference because it creates regular, well-behaved classes.
117
118 :::{admonition} Summary
119 If you want a *tuple with names*, by all means: go for a `namedtuple`.[^perf]
120 But if you want a class with methods, you're doing yourself a disservice by relying on a pile of hacks that requires you to employ even more hacks as your requirements expand.
121
122 Other than that, *attrs* also adds nifty features like validators, converters, and (mutable!) default values.
123 :::
124
125 [^history]: The word is that `namedtuple`s were added to the Python standard library as a way to make tuples in return values more readable.
126 And indeed that is something you see throughout the standard library.
127
128 Looking at what the makers of `namedtuple`s use it for themselves is a good guideline for deciding on your own use cases.
129
130 [^pollution]: *attrs* only adds a single attribute: `__attrs_attrs__` for introspection.
131 All helpers are functions in the `attr` package.
132 Since they take the instance as first argument, you can easily attach them to your classes under a name of your own choice.
133
134 [^iter]: {func}`attrs.astuple` can be used to get that behavior in *attrs* on *explicit demand*.
135
136 [^immutable]: *attrs* offers *optional* immutability through the `frozen` keyword.
137
138 [^perf]: Although *attrs* would serve you just as well!
139 Since both employ the same method of writing and compiling Python code for you, the performance penalty is negligible at worst and in some cases *attrs* is even faster if you use `slots=True` (which is generally a good idea anyway).
140
141
142 ## … tuples?
143
144 ### Readability
145
146 What makes more sense while debugging:
147
148 ```
149 Point(x=1, y=2)
150 ```
151
152 or:
153
154 ```
155 (1, 2)
156 ```
157
158 ?
159
160 Let's add even more ambiguity:
161
162 ```
163 Customer(id=42, reseller=23, first_name="Jane", last_name="John")
164 ```
165
166 or:
167
168 ```
169 (42, 23, "Jane", "John")
170 ```
171
172 ?
173
174 Why would you want to write `customer[2]` instead of `customer.first_name`?
175
176 Don't get me started when you add nesting.
177 If you've never run into mysterious tuples you had no idea what the hell they meant while debugging, you're much smarter than yours truly.
178
179 Using proper classes with names and types makes program code much more readable and [comprehensible](https://arxiv.org/pdf/1304.5257.pdf).
180 Especially when trying to grok a new piece of software or returning to old code after several months.
181
182
183 ### Extendability
184
185 Imagine you have a function that takes or returns a tuple.
186 Especially if you use tuple unpacking (eg. `x, y = get_point()`), adding additional data means that you have to change the invocation of that function *everywhere*.
187
188 Adding an attribute to a class concerns only those who actually care about that attribute.
189
190
191 ## … dicts?
192
193 Dictionaries are not for fixed fields.
194
195 If you have a dict, it maps something to something else.
196 You should be able to add and remove values.
197
198 *attrs* lets you be specific about those expectations; a dictionary does not.
199 It gives you a named entity (the class) in your code, which lets you explain in other places whether you take a parameter of that class or return a value of that class.
200
201 In other words: if your dict has a fixed and known set of keys, it is an object, not a hash.
202 So if you never iterate over the keys of a dict, you should use a proper class.
203
204
205 ## … hand-written classes?
206
207 While we're fans of all things artisanal, writing the same nine methods again and again doesn't qualify.
208 I usually manage to get some typos inside and there's simply more code that can break and thus has to be tested.
209
210 To bring it into perspective, the equivalent of
211
212 ```{doctest}
213 >>> @attrs.define
214 ... class SmartClass:
215 ... a = attrs.field()
216 ... b = attrs.field()
217 >>> SmartClass(1, 2)
218 SmartClass(a=1, b=2)
219 ```
220
221 is roughly
222
223 ```{doctest}
224 >>> class ArtisanalClass:
225 ... def __init__(self, a, b):
226 ... self.a = a
227 ... self.b = b
228 ...
229 ... def __repr__(self):
230 ... return f"ArtisanalClass(a={self.a}, b={self.b})"
231 ...
232 ... def __eq__(self, other):
233 ... if other.__class__ is self.__class__:
234 ... return (self.a, self.b) == (other.a, other.b)
235 ... else:
236 ... return NotImplemented
237 ...
238 ... def __ne__(self, other):
239 ... result = self.__eq__(other)
240 ... if result is NotImplemented:
241 ... return NotImplemented
242 ... else:
243 ... return not result
244 ...
245 ... def __lt__(self, other):
246 ... if other.__class__ is self.__class__:
247 ... return (self.a, self.b) < (other.a, other.b)
248 ... else:
249 ... return NotImplemented
250 ...
251 ... def __le__(self, other):
252 ... if other.__class__ is self.__class__:
253 ... return (self.a, self.b) <= (other.a, other.b)
254 ... else:
255 ... return NotImplemented
256 ...
257 ... def __gt__(self, other):
258 ... if other.__class__ is self.__class__:
259 ... return (self.a, self.b) > (other.a, other.b)
260 ... else:
261 ... return NotImplemented
262 ...
263 ... def __ge__(self, other):
264 ... if other.__class__ is self.__class__:
265 ... return (self.a, self.b) >= (other.a, other.b)
266 ... else:
267 ... return NotImplemented
268 ...
269 ... def __hash__(self):
270 ... return hash((self.__class__, self.a, self.b))
271 >>> ArtisanalClass(a=1, b=2)
272 ArtisanalClass(a=1, b=2)
273 ```
274
275 which is quite a mouthful and it doesn't even use any of *attrs*'s more advanced features like validators or default values.
276 Also: no tests whatsoever.
277 And who will guarantee you, that you don't accidentally flip the `<` in your tenth implementation of `__gt__`?
278
279 It also should be noted that *attrs* is not an all-or-nothing solution.
280 You can freely choose which features you want and disable those that you want more control over:
281
282 ```{doctest}
283 >>> @attrs.define
284 ... class SmartClass:
285 ... a: int
286 ... b: int
287 ...
288 ... def __repr__(self):
289 ... return "<SmartClass(a=%d)>" % (self.a,)
290 >>> SmartClass(1, 2)
291 <SmartClass(a=1)>
292 ```
293
294 :::{admonition} Summary
295 If you don't care and like typing, we're not gonna stop you.
296
297 However it takes a lot of bias and determined rationalization to claim that *attrs* raises the mental burden on a project given how difficult it is to find the important bits in a hand-written class and how annoying it is to ensure you've copy-pasted your code correctly over all your classes.
298
299 In any case, if you ever get sick of the repetitiveness and the drowning of important code in a sea of boilerplate, *attrs* will be waiting for you.
300 :::