Debian Codegraph @

docs/learning-from-bidict.rst

raw
1 Learning from ``bidict``
2 ------------------------
3
4 Working on bidict has taken me to
5 some of the most interesting and unexpected places
6 I've gotten to visit in many years of programming.
7 (When I started this project 20 years ago,
8 I'd never heard of things like higher-kinded types.
9 Thanks to bidict, I not only learned about them,
10 I got to `share a practical example with Guido
11 <https://github.com/python/typing/issues/548#issuecomment-621195693>`__
12 where they would be beneficial for Python.)
13
14 The problem space that bidict inhabits
15 is abundant with beautiful symmetries,
16 delightful surprises, and rich opportunities
17 to come up with elegant solutions.
18
19 You can check out bidict's source
20 to see for yourself.
21 I've sought to optimize the code
22 not just for correctness and performance,
23 but also for clarity, maintainability,
24 and to make for an enjoyable read.
25
26 See below for more, and feel free to
27 let me know what you think.
28 I hope reading bidict's code
29 brings you some of the
30 `joy <https://joy.recurse.com/posts/148-bidict>`__
31 that bidict has brought me.
32
33
34 Code structure
35 ==============
36
37 :class:`~bidict.bidict`\s come in
38 mutable, immutable, and ordered variants,
39 implementing Python's various
40 :class:`relevant <collections.abc.Mapping>`
41 :class:`collections <collections.abc.MutableMapping>`
42 :class:`interfaces <collections.abc.Hashable>`
43 as appropriate.
44
45 Factoring the code to maximize reuse, modularity, and
46 adherence to `SOLID <https://en.wikipedia.org/wiki/SOLID>`__ design principles
47 (while not missing any chances for specialized optimizations)
48 has been one of the most fun parts of working on bidict.
49
50 To see how this is done, check out the code starting with
51 `__init__.py <https://github.com/jab/bidict/blob/main/bidict/__init__.py#L9>`__,
52 and then follow the path suggested in the "code review nav" comments at the
53 top of the file:
54
55 - `_base.py <https://github.com/jab/bidict/blob/main/bidict/_base.py#L8>`__
56 - `_frozen.py <https://github.com/jab/bidict/blob/main/bidict/_frozen.py#L8>`__
57 - `_bidict.py <https://github.com/jab/bidict/blob/main/bidict/_bidict.py#L8>`__
58 - `_orderedbase.py <https://github.com/jab/bidict/blob/main/bidict/_orderedbase.py#L8>`__
59 - `_orderedbidict.py <https://github.com/jab/bidict/blob/main/bidict/_orderedbidict.py#L8>`__
60
61
62 Data structures are amazing
63 ===========================
64
65 Data structures are one of the most fascinating and important
66 building blocks of programming and computer science.
67
68 It's all too easy to lose sight of the magic when having to implement them
69 for computer science courses or job interview questions.
70 Part of this is because many of the most interesting real-world details get left out,
71 and you miss all the value that comes from ongoing, direct practical application.
72
73 Bidict shows how fundamental data structures
74 can be implemented in Python for real-world usage,
75 with practical concerns at top of mind.
76
77
78 ``OrderedBidict``\'s design
79 ===========================
80
81 A regular :class:`~bidict.bidict`
82 encapsulates two regular dicts,
83 keeping them in sync to preserve the bidirectional mapping invariants.
84 How should we extend this to implement :class:`~bidict.OrderedBidict`?
85
86 From :class:`~bidict.BidictBase`,
87 :class:`~bidict.OrderedBidictBase` inherits the use of two regular dicts
88 to store the contents of the forward and inverse items.
89
90 To store the *ordering* of the items,
91 we use a doubly-linked list
92 (much like :class:`~collections.OrderedDict`),
93 allowing us to e.g. move any item to the front
94 of the bidict in constant time.
95
96 Interestingly, the nodes of the linked list encode only the ordering of the items;
97 the nodes themselves contain no key or value data.
98 An additional backing mapping associates the key/value data
99 with the nodes, providing the final piece of the puzzle.
100
101 And since the implementation needs to not only
102 look up nodes by key/value, but also key/value by node,
103 we use a :class:`~bidict.bidict` for this internally.
104 Bidicts all the way down!
105
106
107 Python syntax hacks
108 ===================
109
110 bidict :issue:`used to <19>` support
111 a specialized form of Python's :ref:`slice <slicings>` syntax
112 for getting and setting keys by value:
113
114 .. code-block:: python
115
116 element_by_symbol = bidict(H='hydrogen')
117 # [normal] syntax for the forward mapping lookup:
118 element_by_symbol['H'] # ==> 'hydrogen'
119 # [:slice] syntax for the inverse lookup (no longer supported):
120 element_by_symbol[:'hydrogen'] # ==> 'H'
121
122
123 See `this code <https://github.com/jab/bidict/blob/356dbe3/bidict/_bidict.py#L25>`__
124 for how this was implemented.
125
126 It's super cool when you find a way to bend Python's syntax
127 to support new use cases like this
128 that still feel like they fit well into the language,
129 especially given that Python (wisely) limits
130 how much you can customize its syntax.
131
132
133 Property-based testing is incredible
134 ====================================
135
136 When your automated tests run,
137 are they only checking the test cases
138 that you happened to think of when writing your tests?
139 How do you know you aren't missing
140 some important edge cases?
141
142 With property-based testing,
143 you describe the _types_ of the test case inputs that your APIs accept,
144 along with the properties that should hold for all valid inputs.
145 Rather than having to think of your test case inputs manually
146 and hard-code them into your test suite,
147 they get generated for you dynamically,
148 in much greater quantity and diversity
149 than you would typically come up with by hand.
150 This dramatically increases test coverage
151 and confidence that your code is correct
152 with much less actual test code.
153
154 Bidict never would have survived so many refactorings with so few bugs
155 if it weren't for property-based testing, enabled by the amazing
156 `Hypothesis <https://hypothesis.readthedocs.io>`__ library.
157
158 Check out `bidict's property-based tests
159 <https://github.com/jab/bidict/blob/main/tests/test_bidict.py>`__
160 to see this in action.
161
162
163 Python surprises
164 ================
165
166 - What should happen when checking equality of several ordered mappings
167 that contain the same items but in a different order?
168
169 First let's see how :class:`collections.OrderedDict` works.
170 The results may surprise you:
171
172 .. doctest::
173
174 >>> from collections import OrderedDict
175 >>> x = OrderedDict({1: 1, 2: 2})
176 >>> y = {1: 1, 2: 2}
177 >>> z = OrderedDict({2: 2, 1: 1})
178 >>> x == y
179 True
180 >>> y == z
181 True
182 >>> x == z # !!!
183 False
184
185 So :class:`collections.OrderedDict` violates the
186 `transitive property of equality
187 <https://en.wikipedia.org/wiki/Equality_(mathematics)#Basic_properties>`__.
188 This can lead to some even more unusual behavior than the above.
189 As an example, let's see what would happen if
190 ``bidict.frozenbidict.__eq__()``
191 behaved this way:
192
193 .. doctest::
194
195 >>> class BadFrozenBidict(BidictBase):
196 ... __hash__ = frozenbidict.__hash__
197 ...
198 ... def __eq__(self, other): # (deliberately simplified)
199 ... # Override to be order-sensitive, like collections.OrderedDict:
200 ... return all(i == j for (i, j) in zip(self.items(), other.items()))
201
202
203 >>> x = BadFrozenBidict({1: 1, 2: 2})
204 >>> y = frozenbidict({1: 1, 2: 2})
205 >>> z = BadFrozenBidict({2: 2, 1: 1})
206 >>> x == y
207 True
208 >>> y == z
209 True
210 >>> x == z # !!!
211 False
212 >>> set1 = {x, y, z}
213 >>> len(set1)
214 2
215 >>> set2 = {y, x, z}
216 >>> len(set2) # !!!
217 1
218
219 According to Raymond Hettinger,
220 the Python core developer who built Python's collections foundation,
221 :class:`collections.OrderedDict`\'s ``__eq__()`` implementation
222 should have been order-insensitive.
223 Making it order-sensitive violates the transitive property of equality
224 as well as the `Liskov substitution principle
225 <https://en.wikipedia.org/wiki/Liskov_substitution_principle>`__.
226 It's too late now to change this for :class:`collections.OrderedDict`.
227
228 But at least it's not too late to learn from this.
229 Hence :ref:`eq-order-insensitive`, even for ordered bidicts.
230 For an order-sensitive equality check, bidict provides the separate
231 :meth:`~bidict.BidictBase.equals_order_sensitive` method,
232 thanks to Raymond's advice.
233
234 - See :ref:`addendum:\*nan\* as a Key`.
235
236 - See :ref:`addendum:Equivalent but distinct \:class\:\`~collections.abc.Hashable\`\\s`.
237
238
239 Better memory usage through ``__slots__``
240 =========================================
241
242 Using :ref:`slots` speeds up attribute access,
243 and can dramatically reduce memory usage in CPython
244 when creating many instances of the same class.
245
246 As an example,
247 the ``Node`` class used internally
248 (in the linked list that backs
249 :class:`~bidict.OrderedBidictBase`)
250 uses slots for better performance at scale,
251 since there are as many node instances kept in memory
252 as there are items in every ordered bidict in memory.
253 *See:* `_orderedbase.py <https://github.com/jab/bidict/blob/main/bidict/_orderedbase.py#L8>`__
254
255 Note that extra care must be taken
256 when using slots with pickling and weakrefs;
257 see the code for more.
258
259
260 Better memory usage through ``weakref``
261 =======================================
262
263 A :class:`~bidict.bidict` and its inverse use :mod:`weakref` to
264 :ref:`avoid creating a reference cycle
265 <addendum:\`\`bidict\`\` Avoids Reference Cycles>`.
266 As a result, when you drop your last reference to a bidict,
267 its memory is reclaimed immediately in CPython
268 rather than having to wait for the next garbage collection.
269 *See:* `_base.py <https://github.com/jab/bidict/blob/main/bidict/_base.py#L8>`__
270
271 As another example,
272 the ``Node`` class used internally by
273 :class:`~bidict.OrderedBidictBase`
274 uses weakrefs to avoid creating reference cycles
275 in the doubly-linked lists used
276 to encode the ordering of inserted items.
277 *See:* `_orderedbase.py <https://github.com/jab/bidict/blob/main/bidict/_orderedbase.py#L8>`__
278
279
280 Using descriptors for managed attributes
281 ========================================
282
283 To abstract the details of creating and dereferencing
284 the weakrefs that :class:`~bidict.OrderedBidictBase`\'s
285 aforementioned doubly-linked list nodes use
286 to refer to their neighbor nodes,
287 a ``WeakAttr`` descriptor is used to
288 `manage access to these attributes automatically
289 <https://docs.python.org/3/howto/descriptor.html#managed-attributes>`__.
290 *See:* `_orderedbase.py <https://github.com/jab/bidict/blob/main/bidict/_orderedbase.py#L8>`__
291
292
293 The implicit ``__class__`` reference
294 ====================================
295
296 Anytime you have to reference the exact class of an instance
297 (and not a potential subclass) from within a method body,
298 you can use the implicit, lexically-scoped ``__class__`` reference
299 rather than hard-coding the current class's name.
300 *See:* https://docs.python.org/3/reference/datamodel.html#executing-the-class-body
301
302
303 Subclassing ``namedtuple`` classes
304 ==================================
305
306 To get the performance benefits, intrinsic sortability, etc.
307 of :class:`~typing.NamedTuple` (or :func:`~collections.namedtuple`)
308 while customizing behavior, API, etc.,
309 you can subclass.
310
311 See the *OnDup* class in
312 `_dup.py <https://github.com/jab/bidict/blob/main/bidict/_dup.py>`__
313 for an example.
314
315 Here's another example:
316
317 .. doctest::
318
319 >>> from collections import namedtuple
320 >>> from itertools import count
321
322 >>> class Node(namedtuple('_Node', 'cost tiebreaker data parent depth')):
323 ... """Represent nodes in a graph traversal. Suitable for use with e.g. heapq."""
324 ...
325 ... __slots__ = ()
326 ... _counter = count() # break ties between equal-cost nodes, avoid comparing data
327 ...
328 ... # Give call sites a cleaner API for creating new Nodes
329 ... def __new__(cls, cost, data, parent=None):
330 ... tiebreaker = next(cls._counter)
331 ... depth = parent.depth + 1 if parent else 0
332 ... return super().__new__(cls, cost, tiebreaker, data, parent, depth)
333 ...
334 ... def __repr__(self):
335 ... return 'Node(cost={cost}, data={data!r})'.format(**self._asdict())
336
337 >>> start = Node(cost=0, data='foo')
338 >>> child = Node(cost=5, data='bar', parent=start)
339 >>> child
340 Node(cost=5, data='bar')
341 >>> child.parent
342 Node(cost=0, data='foo')
343 >>> child.depth
344 1
345
346
347 ``namedtuple``-style dynamic class generation
348 =============================================
349
350 See the `implementation
351 <https://github.com/jab/bidict/blob/f4823c7/bidict/_named.py>`__
352 of ``namedbidict`` (it was since removed due to low usage).
353
354
355 API Design
356 ==========
357
358 How to deeply integrate with Python's :mod:`collections` and other built-in APIs?
359
360 - Beyond implementing :class:`collections.abc.Mapping`,
361 bidicts implement additional APIs
362 that :class:`dict` and :class:`~collections.OrderedDict` implement
363 (e.g. ``setdefault()``, ``popitem()``, etc.).
364
365 - When creating a new API, making it familiar, memorable, and intuitive
366 is hugely important to a good user experience.
367
368 - Thanks to :class:`~collections.abc.Hashable`'s
369 implementing :meth:`abc.ABCMeta.__subclasshook__`,
370 any class that implements the required methods of the
371 :class:`~collections.abc.Hashable` interface
372 (namely, ``__hash__()``)
373 makes it a virtual subclass already, no need to explicitly extend.
374 I.e. As long as ``Foo`` implements a ``__hash__()`` method,
375 ``issubclass(Foo, Hashable)`` will always be True,
376 no need to explicitly subclass via ``class Foo(Hashable): ...``
377
378 - How to make your own open ABC like :class:`~collections.abc.Hashable`?
379
380 - Override :meth:`~abc.ABCMeta.__subclasshook__`
381 to check for the interface you require.
382
383 - Interesting consequence of the ``__subclasshook__()`` design:
384 the "subclass" relation becomes intransitive.
385 e.g. :class:`object` is a subclass of :class:`~collections.abc.Hashable`,
386 :class:`list` is a subclass of :class:`object`,
387 but :class:`list` is not a subclass of :class:`~collections.abc.Hashable`.
388
389 - What if you needed to derive from a second metaclass?
390 Be careful to avoid
391 "TypeError: metaclass conflict: the metaclass of a derived class
392 must be a (non-strict) subclass of the metaclasses of all its bases".
393 See the great write-up in
394 https://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/.
395
396 - :class:`collections.abc.Mapping` and
397 :class:`collections.abc.MutableMapping`
398 don't implement :meth:`~abc.ABCMeta.__subclasshook__`,
399 so you must either explicitly subclass them
400 (in which case you inherit their concrete method implementations)
401 or use :meth:`abc.ABCMeta.register`
402 (to register as a virtual subclass without inheriting any of the implementation).
403
404 - Notice that Python provides :class:`collections.abc.Reversible`
405 but no ``collections.abc.Ordered`` or ``collections.abc.OrderedMapping``.
406 *See:* `<https://bugs.python.org/issue28912>`__
407
408 - See the `Zen of Python <https://www.python.org/dev/peps/pep-0020/>`__
409 for how to make APIs Pythonic.
410
411 The following Zen of Python guidelines have been particularly influential for bidict:
412 - "Errors should never pass silently. Unless explicitly silenced.
413 - "In the face of ambiguity, refuse the temptation to guess."
414 - "Readability counts."
415 - "There should be one – and preferably only one – obvious way to do it."
416
417
418 Python's data model
419 ===================
420
421 - What happens when you implement a custom :meth:`~object.__eq__`?
422 e.g. What's the difference between ``a == b`` and ``b == a``
423 when only ``a`` is an instance of your class?
424 See the great write-up in https://eev.ee/blog/2012/03/24/python-faq-equality/
425 for the answer.
426
427 - Making an immutable type hashable
428 (so it can be inserted into :class:`dict`\s and :class:`set`\s):
429 Must implement :meth:`~object.__hash__` such that
430 ``a == b ⇒ hash(a) == hash(b)``.
431 See the :meth:`object.__hash__` and :meth:`object.__eq__` docs, and
432 the `implementation <https://github.com/jab/bidict/blob/main/bidict/_frozenbidict.py#L8>`__
433 of :class:`~bidict.frozenbidict`.
434
435 - Consider :class:`~bidict.frozenbidict`:
436 its ``__eq__()``
437 is :ref:`order-insensitive <eq-order-insensitive>`.
438 So all contained items must participate in the hash order-insensitively.
439
440 - Can use `collections.abc.Set._hash
441 <https://github.com/python/cpython/blob/v3.10.2/Lib/_collections_abc.py#L674>`__
442 which provides a pure Python implementation of the same hash algorithm
443 used to hash :class:`frozenset`\s.
444 (Since :class:`~collections.abc.ItemsView` extends
445 :class:`~collections.abc.Set`,
446 :meth:`bidict.frozenbidict.__hash__`
447 just calls ``ItemsView(self)._hash()``.)
448
449 - See also `<https://bugs.python.org/issue46684>`__
450
451 - Unlike other attributes, if a class implements ``__hash__()``,
452 any subclasses of that class will not inherit it.
453 It's like Python implicitly adds ``__hash__ = None`` to the body
454 of every class that doesn't explicitly define ``__hash__``.
455 So if you do want a subclass to inherit a base class's ``__hash__()``
456 implementation, you have to set that manually,
457 e.g. by adding ``__hash__ = BaseClass.__hash__`` in the class body.
458
459 This is consistent with the fact that
460 :class:`object` implements ``__hash__()``,
461 but subclasses of :class:`object`
462 that override :meth:`~object.__eq__`
463 are not hashable by default.
464
465 - Overriding :meth:`object.__getattribute__` for custom attribute lookup.
466 See :ref:`extending:\`\`SortedBidict\`\` Recipes`.
467
468 - Using
469 :meth:`object.__getstate__`,
470 :meth:`object.__setstate__`, and
471 :meth:`object.__reduce__` to make an object pickleable
472 that otherwise wouldn't be,
473 due to e.g. using weakrefs,
474 as bidicts do (covered further below).
475
476
477 Portability
478 ===========
479
480 - CPython vs. PyPy (and other Python implementations)
481
482 - See https://doc.pypy.org/en/latest/cpython_differences.html
483
484 - gc / weakref
485
486 - Hence ``test_bidicts_freed_on_zero_refcount()``
487 in `test_properties.py
488 <https://github.com/jab/bidict/blob/main/tests/property_tests/test_properties.py>`__
489 is skipped outside CPython.
490
491 - primitives' identities, nan, etc.
492
493 - Python 2 vs. Python 3
494
495 - As affects bidict, mostly :class:`dict` API changes,
496 but also functions like :func:`zip`, :func:`map`, :func:`filter`, etc.
497
498 - :meth:`~object.__ne__` fixed in Python 3
499
500 - Borrowing methods from other classes:
501
502 In Python 2, must grab the ``.im_func`` / ``__func__``
503 attribute off the borrowed method to avoid getting
504 ``TypeError: unbound method ...() must be called with ... instance as first argument``
505
506
507 Other interesting stuff in the standard library
508 ===============================================
509
510 - :mod:`reprlib` and :func:`reprlib.recursive_repr`
511 (but not needed for bidict because there's no way to insert a bidict into itself)
512 - :func:`operator.methodcaller`
513 - See :ref:`addendum:Missing \`\`bidict\`\`\\s in the Standard Library`
514
515
516 Tools
517 =====
518
519 See the :ref:`Thanks <thanks:Projects>` page for some of the fantastic tools
520 for software verification, performance, code quality, etc.
521 that bidict has provided a great opportunity to learn and use.