| 1 |
Addendum |
| 2 |
======== |
| 3 |
|
| 4 |
Performance |
| 5 |
----------- |
| 6 |
|
| 7 |
Bidict is written to be as performant as possible |
| 8 |
without sacrificing other important goals, |
| 9 |
such as safety, portability, and maintainability. |
| 10 |
|
| 11 |
In general, using a bidict to maintain a bidirectional mapping |
| 12 |
should exhibit about the same performance as |
| 13 |
keeping two mutually-inverse one-directional mappings |
| 14 |
in sync manually. |
| 15 |
The test suite includes benchmarks so that bidict's performance |
| 16 |
can be continuously measured and improved. |
| 17 |
|
| 18 |
If you spot an opportunity to improve bidict's performance further, |
| 19 |
please don't hesitate to |
| 20 |
:doc:`file an issue or submit a pull request <contributors-guide>`. |
| 21 |
|
| 22 |
|
| 23 |
``bidict`` Avoids Reference Cycles |
| 24 |
---------------------------------- |
| 25 |
|
| 26 |
A careful reader might notice the following... |
| 27 |
|
| 28 |
.. doctest:: |
| 29 |
|
| 30 |
>>> fwd = bidict(one=1) |
| 31 |
>>> inv = fwd.inverse |
| 32 |
>>> inv.inverse is fwd |
| 33 |
True |
| 34 |
|
| 35 |
...and worry that a :class:`~bidict.bidict` and its inverse |
| 36 |
create a reference cycle. |
| 37 |
If this were true, |
| 38 |
in CPython this would mean that the memory for a :class:`~bidict.bidict` |
| 39 |
could not be immediately reclaimed when you retained no more references to it, |
| 40 |
but rather would have to wait for the next garbage collection to kick in |
| 41 |
before it could be reclaimed. |
| 42 |
|
| 43 |
However, :class:`~bidict.bidict`\s use a :class:`weakref.ref` |
| 44 |
to store the inverse reference in one direction, |
| 45 |
avoiding the strong reference cycle. |
| 46 |
As a result, when you no longer retain |
| 47 |
any references to a :class:`~bidict.bidict` you create, |
| 48 |
you can be sure that its refcount in CPython drops to zero, |
| 49 |
and that its memory will therefore be reclaimed immediately. |
| 50 |
|
| 51 |
.. note:: |
| 52 |
|
| 53 |
In PyPy this does not occur, as PyPy doesn't use reference counts. |
| 54 |
The memory for unreferenced objects in PyPy is only reclaimed |
| 55 |
when GC kicks in, which is unpredictable. |
| 56 |
|
| 57 |
|
| 58 |
Terminology |
| 59 |
----------- |
| 60 |
|
| 61 |
- It's intentional that the term "inverse" is used rather than "reverse". |
| 62 |
|
| 63 |
Consider a collection of *(k, v)* pairs. |
| 64 |
Taking the reverse of the collection can only be done if it is ordered, |
| 65 |
and (as you'd expect) reverses the order of the pairs in the collection. |
| 66 |
But each original *(k, v)* pair remains in the resulting collection. |
| 67 |
|
| 68 |
By contrast, taking the inverse of such a collection |
| 69 |
neither requires the collection to be ordered |
| 70 |
nor guarantees any ordering in the result, |
| 71 |
but rather just replaces every *(k, v)* pair |
| 72 |
with the inverse pair *(v, k)*. |
| 73 |
|
| 74 |
- "keys" and "values" could perhaps more properly be called |
| 75 |
"primary keys" and "secondary keys" (as in a database), |
| 76 |
or even "forward keys" and "inverse keys", respectively. |
| 77 |
:mod:`bidict` sticks with the terms "keys" and "values" |
| 78 |
for the sake of familiarity and to avoid potential confusion, |
| 79 |
but technically values are also keys themselves. |
| 80 |
|
| 81 |
Concretely, this allows :class:`~bidict.bidict`\s |
| 82 |
to return a set-like (*dict_keys*) object |
| 83 |
for :meth:`~bidict.BidictBase.values`, |
| 84 |
rather than a non-set-like *dict_values* object. |
| 85 |
|
| 86 |
|
| 87 |
Missing ``bidict``\s in the Standard Library |
| 88 |
-------------------------------------------- |
| 89 |
|
| 90 |
The Python standard library actually contains some examples |
| 91 |
where :class:`~bidict.bidict`\s could be used for fun and profit |
| 92 |
(depending on your ideas of fun and profit): |
| 93 |
|
| 94 |
- The :mod:`logging` module |
| 95 |
contains a private ``_levelToName`` dict |
| 96 |
which maps integer levels like *10* to their string names like *DEBUG*. |
| 97 |
If I had a nickel for every time I wanted that exposed in a bidirectional map |
| 98 |
(and as a public attribute, no less), |
| 99 |
I bet I could afford some better turns of phrase. |
| 100 |
|
| 101 |
- The :mod:`dis` module |
| 102 |
maintains a mapping from opnames to opcodes |
| 103 |
``dis.opmap`` |
| 104 |
and a separate list of opnames indexed by opcode |
| 105 |
``dis.opnames``. |
| 106 |
These could be combined into a single bidict. |
| 107 |
|
| 108 |
- The :mod:`html.entities` module |
| 109 |
maintains separate |
| 110 |
``html.entities.name2codepoint`` and |
| 111 |
``html.entities.codepoint2name`` dicts. |
| 112 |
These could be combined into a single bidict. |
| 113 |
|
| 114 |
|
| 115 |
Caveats |
| 116 |
------- |
| 117 |
|
| 118 |
Non-Atomic Mutation |
| 119 |
^^^^^^^^^^^^^^^^^^^ |
| 120 |
|
| 121 |
As with built-in dicts, |
| 122 |
mutating operations on a :class:`~bidict.bidict` are not atomic. |
| 123 |
If you need to mutate the same :class:`~bidict.bidict` from different threads, |
| 124 |
use a |
| 125 |
`synchronization primitive <https://docs.python.org/3/library/threading.html#lock-objects>`__ |
| 126 |
to coordinate access. [#]_ |
| 127 |
|
| 128 |
.. [#] *See also:* |
| 129 |
[`2 <https://twitter.com/teozaurus/status/518071391959388160>`__], |
| 130 |
[`3 <https://twitter.com/ph1/status/943240854419922945>`__] |
| 131 |
|
| 132 |
|
| 133 |
Equivalent but distinct :class:`~collections.abc.Hashable`\s |
| 134 |
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 135 |
|
| 136 |
Consider the following: |
| 137 |
|
| 138 |
.. doctest:: |
| 139 |
|
| 140 |
>>> d = {1: int, 1.0: float} |
| 141 |
|
| 142 |
How many items do you expect *d* to contain? |
| 143 |
The actual result might surprise you: |
| 144 |
|
| 145 |
.. doctest:: |
| 146 |
|
| 147 |
>>> len(d) |
| 148 |
1 |
| 149 |
|
| 150 |
And similarly, |
| 151 |
|
| 152 |
.. doctest:: |
| 153 |
|
| 154 |
>>> {1: int, 1.0: float, 1+0j: complex, True: bool} |
| 155 |
{1: <class 'bool'>} |
| 156 |
>>> 1+0j in {True} |
| 157 |
True |
| 158 |
|
| 159 |
(Note that ``1 == 1.0 == 1+0j == True``.) |
| 160 |
|
| 161 |
This illustrates that a mapping cannot contain two items |
| 162 |
with equivalent but distinct keys |
| 163 |
(and likewise a set cannot contain two equivalent but distinct elements). |
| 164 |
If an object that is being looked up in a set or mapping |
| 165 |
is equal to a contained object, |
| 166 |
the contained object will be found, |
| 167 |
even if it is distinct. |
| 168 |
|
| 169 |
With a :class:`~bidict.bidict`, |
| 170 |
since values function as keys in the inverse mapping, |
| 171 |
this behavior occurs in the inverse direction too. |
| 172 |
|
| 173 |
That puts a :class:`~bidict.bidict` between two of :class:`dict`'s conventions, |
| 174 |
which conflict once a value is also a key: |
| 175 |
overwriting a :class:`dict` key keeps the key object already contained, |
| 176 |
but replaces the value object with the one passed in. |
| 177 |
A :class:`~bidict.bidict` resolves this |
| 178 |
by keeping the object already contained in both directions, |
| 179 |
so that a single item is never represented by |
| 180 |
two equivalent but distinct objects: |
| 181 |
|
| 182 |
.. doctest:: |
| 183 |
|
| 184 |
>>> b = bidict({'false': 0}) |
| 185 |
>>> b.forceput('FALSE', False) |
| 186 |
>>> b # the contained 0 is kept, rather than the equivalent False passed in |
| 187 |
bidict({'FALSE': 0}) |
| 188 |
>>> b.inverse |
| 189 |
bidict({0: 'FALSE'}) |
| 190 |
>>> b.inverse[b['FALSE']] is next(iter(b)) # one object per item, in both directions |
| 191 |
True |
| 192 |
|
| 193 |
|
| 194 |
*nan* as a Key |
| 195 |
^^^^^^^^^^^^^^ |
| 196 |
|
| 197 |
In CPython, *nan* is especially tricky when used as a dictionary key: |
| 198 |
|
| 199 |
.. doctest:: |
| 200 |
|
| 201 |
>>> d = {float('nan'): 'nan'} |
| 202 |
>>> d |
| 203 |
{nan: 'nan'} |
| 204 |
>>> d[float('nan')] # doctest: +SKIP |
| 205 |
Traceback (most recent call last): |
| 206 |
... |
| 207 |
KeyError: nan |
| 208 |
>>> d[float('nan')] = 'not overwritten' |
| 209 |
>>> d # doctest: +SKIP |
| 210 |
{nan: 'nan', nan: 'not overwritten'} |
| 211 |
|
| 212 |
In other Python implementations such as PyPy, |
| 213 |
*nan* behaves just like any other dictionary key. |
| 214 |
But in CPython, beware of this unexpected behavior, |
| 215 |
which applies to :class:`~bidict.bidict`\s too. |
| 216 |
:mod:`bidict` contains no special-case logic |
| 217 |
for dealing with *nan* as a key, |
| 218 |
so bidict's behavior will match :class:`dict`'s |
| 219 |
on whatever runtime you're using. |
| 220 |
|
| 221 |
Note that even though *nan* is not equal to itself, |
| 222 |
re-inserting an already-contained item using the same *nan* object |
| 223 |
is still construed as a no-op |
| 224 |
(see :ref:`basic-usage:Key and Value Duplication`): |
| 225 |
|
| 226 |
.. doctest:: |
| 227 |
|
| 228 |
>>> b = bidict() |
| 229 |
>>> nan = float('nan') |
| 230 |
>>> b[nan] = 'nan' |
| 231 |
>>> b[nan] = 'nan' # no-op |
| 232 |
>>> b |
| 233 |
bidict({nan: 'nan'}) |
| 234 |
|
| 235 |
See e.g. `these docs |
| 236 |
<https://doc.pypy.org/en/latest/cpython_differences.html>`__ |
| 237 |
for more info (search the page for "nan"). |
| 238 |
|
| 239 |
|
| 240 |
Simultaneous Assignment |
| 241 |
^^^^^^^^^^^^^^^^^^^^^^^ |
| 242 |
|
| 243 |
:class:`~bidict.bidict`\s may behave differently |
| 244 |
from dicts with respect to so-called "simultaneous assignment". |
| 245 |
|
| 246 |
Consider the following: |
| 247 |
|
| 248 |
.. doctest:: |
| 249 |
|
| 250 |
>>> m = {'a': 'a', 'b': 'b'} |
| 251 |
>>> m['a'], m['b'] = m['b'], m['a'] # swap two values |
| 252 |
>>> m |
| 253 |
{'a': 'b', 'b': 'a'} |
| 254 |
|
| 255 |
With a :class:`~bidict.bidict`, |
| 256 |
simultaneous assignment cannot be used |
| 257 |
to swap two values in this way: |
| 258 |
|
| 259 |
.. doctest:: |
| 260 |
|
| 261 |
>>> m = bidict({'a': 'a', 'b': 'b'}) |
| 262 |
>>> m['a'], m['b'] = m['b'], m['a'] |
| 263 |
Traceback (most recent call last): |
| 264 |
... |
| 265 |
bidict.KeyAndValueDuplicationError: ('a', 'b') |
| 266 |
|
| 267 |
This is because "simultaneous" assignments like the above |
| 268 |
are `by definition <https://docs.python.org/3/reference/simple_stmts.html#assignment-statements>`__ |
| 269 |
just syntax sugar for: |
| 270 |
|
| 271 |
.. code-block:: python |
| 272 |
|
| 273 |
# desugaring: m['a'], m['b'] = m['b'], m['a'] |
| 274 |
tmp = (m['b'], m['a']) |
| 275 |
m['a'] = tmp[0] |
| 276 |
m['b'] = tmp[1] |
| 277 |
|
| 278 |
and so the intermediate ``m['a'] = tmp[0]`` assignment |
| 279 |
raises :class:`~bidict.KeyAndValueDuplicationError` |
| 280 |
before the second half of the swap assignment has a chance to run. |
| 281 |
|
| 282 |
For a working alternative, you can write: |
| 283 |
|
| 284 |
.. doctest:: |
| 285 |
|
| 286 |
>>> m.forceupdate({m['a']: m['b'], m['b']: m['a']}) |
| 287 |
>>> m |
| 288 |
bidict({'a': 'b', 'b': 'a'}) |
| 289 |
|
| 290 |
---- |
| 291 |
|
| 292 |
For more in this vein, |
| 293 |
check out :doc:`learning-from-bidict`. |