| 1 |
Other ``bidict`` Types |
| 2 |
====================== |
| 3 |
|
| 4 |
Now that we've covered |
| 5 |
:doc:`basic-usage` with the :class:`bidict.bidict` type, |
| 6 |
let's look at some other bidirectional mapping types. |
| 7 |
|
| 8 |
|
| 9 |
Bidict Types Diagram |
| 10 |
-------------------- |
| 11 |
|
| 12 |
.. image:: _static/bidict-types-diagram.png |
| 13 |
:target: _static/bidict-types-diagram.png |
| 14 |
:alt: bidict types diagram |
| 15 |
|
| 16 |
All bidirectional mapping types that :mod:`bidict` provides |
| 17 |
are subclasses of :class:`bidict.BidirectionalMapping`. |
| 18 |
This abstract base class |
| 19 |
extends :class:`collections.abc.Mapping` |
| 20 |
by adding the |
| 21 |
":attr:`~bidict.BidirectionalMapping.inverse`" |
| 22 |
:obj:`~abc.abstractproperty`. |
| 23 |
|
| 24 |
As you can see above, |
| 25 |
:class:`bidict.bidict` is also |
| 26 |
a :class:`collections.abc.MutableMapping`. |
| 27 |
But :mod:`bidict` provides |
| 28 |
immutable bidirectional mapping types as well. |
| 29 |
|
| 30 |
|
| 31 |
:class:`~bidict.frozenbidict` |
| 32 |
----------------------------- |
| 33 |
|
| 34 |
:class:`~bidict.frozenbidict` |
| 35 |
is an immutable, hashable bidirectional mapping type. |
| 36 |
|
| 37 |
As you would expect, |
| 38 |
attempting to mutate a |
| 39 |
:class:`~bidict.frozenbidict` |
| 40 |
causes an error: |
| 41 |
|
| 42 |
.. doctest:: |
| 43 |
|
| 44 |
>>> from bidict import frozenbidict |
| 45 |
>>> f = frozenbidict({'H': 'hydrogen'}) |
| 46 |
>>> f['C'] = 'carbon' |
| 47 |
Traceback (most recent call last): |
| 48 |
... |
| 49 |
TypeError: 'frozenbidict' object does not support item assignment |
| 50 |
|
| 51 |
|
| 52 |
:class:`~bidict.frozenbidict` |
| 53 |
also implements :class:`collections.abc.Hashable`, |
| 54 |
so it's suitable for insertion into sets or other mappings: |
| 55 |
|
| 56 |
.. doctest:: |
| 57 |
|
| 58 |
>>> my_set = {f} # not an error |
| 59 |
>>> my_dict = {f: 1} # also not an error |
| 60 |
|
| 61 |
|
| 62 |
:class:`~bidict.OrderedBidict` |
| 63 |
------------------------------ |
| 64 |
|
| 65 |
:class:`bidict.OrderedBidict` |
| 66 |
is a :class:`~bidict.MutableBidirectionalMapping` |
| 67 |
that preserves the insertion order of its items, |
| 68 |
and offers some additional ordering-related APIs |
| 69 |
not offered by the plain bidict type. |
| 70 |
It's like a bidirectional version of :class:`collections.OrderedDict`. |
| 71 |
|
| 72 |
.. doctest:: |
| 73 |
|
| 74 |
>>> from bidict import OrderedBidict |
| 75 |
>>> element_by_symbol = OrderedBidict({'H': 'hydrogen', 'He': 'helium', 'Li': 'lithium'}) |
| 76 |
>>> element_by_symbol.inverse |
| 77 |
OrderedBidict({'hydrogen': 'H', 'helium': 'He', 'lithium': 'Li'}) |
| 78 |
|
| 79 |
>>> first, second, third = element_by_symbol.values() |
| 80 |
>>> first, second, third |
| 81 |
('hydrogen', 'helium', 'lithium') |
| 82 |
|
| 83 |
>>> # Insert an additional item and verify it now comes last: |
| 84 |
>>> element_by_symbol['Be'] = 'beryllium' |
| 85 |
>>> *_, last_item = element_by_symbol.items() |
| 86 |
>>> last_item |
| 87 |
('Be', 'beryllium') |
| 88 |
|
| 89 |
|
| 90 |
.. _extra-order-sensitive-apis: |
| 91 |
|
| 92 |
Extra order-sensitive APIs |
| 93 |
++++++++++++++++++++++++++ |
| 94 |
|
| 95 |
Additional, efficiently-implemented, order-sensitive APIs are provided as well, |
| 96 |
following the example of :class:`~collections.OrderedDict`. |
| 97 |
|
| 98 |
Namely, |
| 99 |
:class:`~bidict.OrderedBidict` provides constant-time implementations of |
| 100 |
:meth:`popitem(last: bool) <bidict.OrderedBidict.popitem>` and |
| 101 |
:meth:`move_to_end(last: bool) <bidict.OrderedBidict.move_to_end>`, |
| 102 |
which make ordered bidicts suitable to use for things like FIFO queues |
| 103 |
and LRU caches. |
| 104 |
|
| 105 |
.. doctest:: |
| 106 |
|
| 107 |
>>> element_by_symbol.popitem(last=True) # Remove the last item |
| 108 |
('Be', 'beryllium') |
| 109 |
>>> element_by_symbol.popitem(last=False) # Remove the first item |
| 110 |
('H', 'hydrogen') |
| 111 |
|
| 112 |
>>> # Re-adding hydrogen after it's been removed moves it to the end: |
| 113 |
>>> element_by_symbol['H'] = 'hydrogen' |
| 114 |
>>> element_by_symbol |
| 115 |
OrderedBidict({'He': 'helium', 'Li': 'lithium', 'H': 'hydrogen'}) |
| 116 |
|
| 117 |
>>> # But there's also a `move_to_end` method just for this purpose: |
| 118 |
>>> element_by_symbol.move_to_end('Li') |
| 119 |
>>> element_by_symbol |
| 120 |
OrderedBidict({'He': 'helium', 'H': 'hydrogen', 'Li': 'lithium'}) |
| 121 |
|
| 122 |
>>> element_by_symbol.move_to_end('H', last=False) # move to front |
| 123 |
>>> element_by_symbol |
| 124 |
OrderedBidict({'H': 'hydrogen', 'He': 'helium', 'Li': 'lithium'}) |
| 125 |
|
| 126 |
|
| 127 |
.. _eq-order-insensitive: |
| 128 |
|
| 129 |
:meth:`~bidict.OrderedBidict`\'s ``__eq__()`` is order-insensitive |
| 130 |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| 131 |
|
| 132 |
To ensure that ``==`` comparison for any bidict always upholds the |
| 133 |
`transitive property of equality |
| 134 |
<https://en.wikipedia.org/wiki/Equality_(mathematics)#Basic_properties>`__ and the |
| 135 |
`Liskov substitution principle <https://en.wikipedia.org/wiki/Liskov_substitution_principle>`__, |
| 136 |
equality tests between a bidict and another mapping |
| 137 |
are always order-insensitive, |
| 138 |
even for ordered bidicts: |
| 139 |
|
| 140 |
.. doctest:: |
| 141 |
|
| 142 |
>>> o1 = OrderedBidict({1: 1, 2: 2}) |
| 143 |
>>> o2 = OrderedBidict({2: 2, 1: 1}) |
| 144 |
>>> o1 == o2 |
| 145 |
True |
| 146 |
|
| 147 |
For order-sensitive equality tests, use |
| 148 |
:meth:`~bidict.BidictBase.equals_order_sensitive`: |
| 149 |
|
| 150 |
.. doctest:: |
| 151 |
|
| 152 |
>>> o1.equals_order_sensitive(o2) |
| 153 |
False |
| 154 |
|
| 155 |
(Note that this improves on the behavior of |
| 156 |
``collections.OrderedDict.__eq__()``. |
| 157 |
For more about this, see |
| 158 |
:ref:`learning-from-bidict:Python surprises`.) |
| 159 |
|
| 160 |
|
| 161 |
What about order-preserving dicts? |
| 162 |
++++++++++++++++++++++++++++++++++ |
| 163 |
|
| 164 |
In CPython 3.6+ and all versions of PyPy, |
| 165 |
:class:`dict` preserves insertion order. |
| 166 |
Since bidicts are built on top of dicts, |
| 167 |
can we get away with |
| 168 |
using a plain bidict |
| 169 |
in places where you need |
| 170 |
an order-preserving bidirectional mapping? |
| 171 |
(Assuming we don't need the :ref:`extra-order-sensitive-apis`.) |
| 172 |
|
| 173 |
Let's look at some examples. |
| 174 |
|
| 175 |
Order consistency between bidicts and their inverses |
| 176 |
++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| 177 |
|
| 178 |
Consider the following: |
| 179 |
|
| 180 |
.. doctest:: |
| 181 |
|
| 182 |
>>> b = bidict({1: -1, 2: -2, 3: -3}) |
| 183 |
>>> b[2] = 'UPDATED' |
| 184 |
>>> b |
| 185 |
bidict({1: -1, 2: 'UPDATED', 3: -3}) |
| 186 |
|
| 187 |
So far so good, but look what happens to the inverse: |
| 188 |
|
| 189 |
.. doctest:: |
| 190 |
|
| 191 |
>>> b.inverse |
| 192 |
bidict({-1: 1, -3: 3, 'UPDATED': 2}) |
| 193 |
|
| 194 |
After the mutation, the ordering of the items |
| 195 |
in the plain bidict is no longer consistent with its inverse. |
| 196 |
|
| 197 |
To ensure that ordering is kept consistent |
| 198 |
between a bidict and its inverse, |
| 199 |
no matter how it's mutated, |
| 200 |
you have to use an ordered bidict: |
| 201 |
|
| 202 |
.. doctest:: |
| 203 |
|
| 204 |
>>> ob = OrderedBidict({1: -1, 2: -2, 3: -3}) |
| 205 |
>>> ob[2] = 'UPDATED' |
| 206 |
>>> ob |
| 207 |
OrderedBidict({1: -1, 2: 'UPDATED', 3: -3}) |
| 208 |
>>> ob.inverse # better: |
| 209 |
OrderedBidict({-1: 1, 'UPDATED': 2, -3: 3}) |
| 210 |
|
| 211 |
|
| 212 |
Preserving insertion order of items even after key changes |
| 213 |
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ |
| 214 |
|
| 215 |
Another way that ordered bidicts differ from plain bidicts |
| 216 |
is that you can change the *key* of an existing item, |
| 217 |
and its order will still be preserved. |
| 218 |
|
| 219 |
Let's look at an example: |
| 220 |
|
| 221 |
.. doctest:: |
| 222 |
|
| 223 |
>>> bi = bidict({1: -1}) |
| 224 |
>>> ob = OrderedBidict({1: -1}) |
| 225 |
>>> bi.forceupdate({2: -2, 3: -1}) |
| 226 |
>>> ob.forceupdate({2: -2, 3: -1}) |
| 227 |
|
| 228 |
This update changes the key of the existing item with value -1. |
| 229 |
In the ordered bidict, this change is performed in-place, |
| 230 |
preserving the insertion order. |
| 231 |
The item with value -1 was the first item inserted, |
| 232 |
and it remains the first item even after the update: |
| 233 |
|
| 234 |
>>> ob |
| 235 |
OrderedBidict({3: -1, 2: -2}) |
| 236 |
|
| 237 |
In the plain bidict, however, |
| 238 |
the changed item has now been moved to the end: |
| 239 |
|
| 240 |
>>> bi |
| 241 |
bidict({2: -2, 3: -1}) |
| 242 |
|
| 243 |
Note that if you insert an item that changes |
| 244 |
the key of one existing item and the value of another existing item, |
| 245 |
the behavior described in |
| 246 |
:ref:`basic-usage:collapsing overwrites` |
| 247 |
still applies. |
| 248 |
|
| 249 |
|
| 250 |
Trade-offs |
| 251 |
++++++++++ |
| 252 |
|
| 253 |
Like plain bidicts (and plain dicts too, for that matter), |
| 254 |
ordered bidicts take *O(n)* space. |
| 255 |
But to preserve insertion order, |
| 256 |
as well as implement the :ref:`extra-order-sensitive-apis` |
| 257 |
in constant time, |
| 258 |
it costs :class:`~bidict.OrderedBidict` |
| 259 |
a higher constant factor in its *O(n)* space complexity. |
| 260 |
|
| 261 |
If you depend on preserving insertion order, |
| 262 |
an unordered bidict may be sufficient if: |
| 263 |
|
| 264 |
* you'll never mutate it |
| 265 |
(in which case, use a :class:`~bidict.frozenbidict`), |
| 266 |
or: |
| 267 |
|
| 268 |
* you only mutate by removing and/or adding whole new items, |
| 269 |
never changing just the key or value of an existing item, |
| 270 |
or: |
| 271 |
|
| 272 |
* you are okay with |
| 273 |
inconsistent ordering between a bidict and its inverse |
| 274 |
after changing the key or value of an existing item, |
| 275 |
as well as with items moving to the end when you change their key |
| 276 |
rather than being changed in place. |
| 277 |
|
| 278 |
That said, if your code depends on the ordering, |
| 279 |
using an :class:`~bidict.OrderedBidict` makes for clearer code, |
| 280 |
and ensures that insertion order will be preserved |
| 281 |
no matter what mutations you perform. |
| 282 |
|
| 283 |
The :ref:`extra-order-sensitive-apis` |
| 284 |
that :class:`~bidict.OrderedBidict` gives you |
| 285 |
also expand the range of use cases |
| 286 |
where your bidict would be suitable, |
| 287 |
as mentioned above. |
| 288 |
|
| 289 |
|
| 290 |
Reversing a bidict |
| 291 |
------------------ |
| 292 |
|
| 293 |
All provided bidict types are reversible |
| 294 |
(since they are backed by dicts, |
| 295 |
which are themselves reversible on all supported Python versions |
| 296 |
as of CPython 3.8+). |
| 297 |
|
| 298 |
.. doctest:: |
| 299 |
|
| 300 |
>>> b = bidict({1: 'one', 2: 'two', 3: 'three'}) |
| 301 |
>>> list(reversed(b)) |
| 302 |
[3, 2, 1] |
| 303 |
>>> list(reversed(b.items())) # keys/values/items views are reversible too |
| 304 |
[(3, 'three'), (2, 'two'), (1, 'one')] |
| 305 |
|
| 306 |
|
| 307 |
Polymorphism |
| 308 |
------------ |
| 309 |
|
| 310 |
Code that needs to check only whether an object is *dict-like* |
| 311 |
should not use ``isinstance(obj, dict)``. |
| 312 |
This check is too specific, because dict-like objects need not |
| 313 |
actually be instances of dict or a dict subclass. |
| 314 |
You can see this for many dict-like objects in the standard library: |
| 315 |
|
| 316 |
.. doctest:: |
| 317 |
|
| 318 |
>>> from collections import ChainMap |
| 319 |
>>> chainmap = ChainMap() |
| 320 |
>>> isinstance(chainmap, dict) |
| 321 |
False |
| 322 |
|
| 323 |
The same is true for all the bidict types: |
| 324 |
|
| 325 |
.. doctest:: |
| 326 |
|
| 327 |
>>> bi = bidict() |
| 328 |
>>> isinstance(bi, dict) |
| 329 |
False |
| 330 |
|
| 331 |
A better way to check whether an object is dict-like |
| 332 |
is to use the :class:`~collections.abc.Mapping` |
| 333 |
abstract base class (ABC) |
| 334 |
from the :mod:`collections.abc` module, |
| 335 |
which provides a number of ABCs |
| 336 |
intended for this purpose: |
| 337 |
|
| 338 |
.. doctest:: |
| 339 |
|
| 340 |
>>> isinstance(chainmap, Mapping) |
| 341 |
True |
| 342 |
>>> isinstance(bi, Mapping) |
| 343 |
True |
| 344 |
|
| 345 |
Also note that the proper way to check whether an object |
| 346 |
is a mutable mapping is to use the |
| 347 |
:class:`~collections.abc.MutableMapping` ABC: |
| 348 |
|
| 349 |
.. doctest:: |
| 350 |
|
| 351 |
>>> isinstance(chainmap, MutableMapping) |
| 352 |
True |
| 353 |
>>> isinstance(bi, MutableMapping) |
| 354 |
True |
| 355 |
|
| 356 |
To illustrate this, |
| 357 |
here's an example of how you can combine the above |
| 358 |
with bidict's own :class:`~bidict.BidirectionalMapping` ABC |
| 359 |
to implement your own check for whether |
| 360 |
an object is an immutable bidirectional mapping: |
| 361 |
|
| 362 |
.. doctest:: |
| 363 |
|
| 364 |
>>> def is_immutable_bimap(obj): |
| 365 |
... return ( |
| 366 |
... isinstance(obj, BidirectionalMapping) |
| 367 |
... and not isinstance(obj, MutableMapping)) |
| 368 |
|
| 369 |
>>> is_immutable_bimap(bidict()) |
| 370 |
False |
| 371 |
|
| 372 |
>>> is_immutable_bimap(frozenbidict()) |
| 373 |
True |
| 374 |
|
| 375 |
For more you can do with :mod:`bidict`, |
| 376 |
check out :doc:`extending` next. |