| 1 |
Basic Usage |
| 2 |
----------- |
| 3 |
|
| 4 |
Let's return to the example from the :doc:`intro`: |
| 5 |
|
| 6 |
.. doctest:: |
| 7 |
|
| 8 |
>>> element_by_symbol = bidict(H='hydrogen') |
| 9 |
|
| 10 |
As we saw, this behaves just like a dict, |
| 11 |
but maintains a special |
| 12 |
:attr:`~bidict.BidictBase.inverse` attribute |
| 13 |
giving access to inverse items: |
| 14 |
|
| 15 |
.. doctest:: |
| 16 |
|
| 17 |
>>> element_by_symbol.inverse |
| 18 |
bidict({'hydrogen': 'H'}) |
| 19 |
>>> element_by_symbol.inverse['helium'] = 'He' |
| 20 |
>>> element_by_symbol |
| 21 |
bidict({'H': 'hydrogen', 'He': 'helium'}) |
| 22 |
>>> del element_by_symbol.inverse['hydrogen'] |
| 23 |
>>> element_by_symbol |
| 24 |
bidict({'He': 'helium'}) |
| 25 |
|
| 26 |
Note you can also use |
| 27 |
:attr:`~bidict.BidictBase.inv` as a shortcut for |
| 28 |
:attr:`~bidict.BidictBase.inverse`: |
| 29 |
|
| 30 |
.. doctest:: |
| 31 |
|
| 32 |
>>> element_by_symbol.inv |
| 33 |
bidict({'helium': 'He'}) |
| 34 |
|
| 35 |
Both a :class:`bidict.bidict` and its inverse |
| 36 |
support the entire |
| 37 |
:class:`collections.abc.MutableMapping` interface: |
| 38 |
|
| 39 |
.. doctest:: |
| 40 |
|
| 41 |
>>> 'C' in element_by_symbol |
| 42 |
False |
| 43 |
>>> element_by_symbol.get('C', 'missing') |
| 44 |
'missing' |
| 45 |
>>> element_by_symbol.pop('He') |
| 46 |
'helium' |
| 47 |
>>> element_by_symbol |
| 48 |
bidict() |
| 49 |
>>> element_by_symbol.update(Hg='mercury') |
| 50 |
>>> element_by_symbol |
| 51 |
bidict({'Hg': 'mercury'}) |
| 52 |
>>> 'mercury' in element_by_symbol.inverse |
| 53 |
True |
| 54 |
>>> element_by_symbol.inverse.pop('mercury') |
| 55 |
'Hg' |
| 56 |
|
| 57 |
The inverse is automatically kept up-to-date. |
| 58 |
Referencing a :class:`~bidict.bidict`'s inverse |
| 59 |
is always a constant-time operation; |
| 60 |
the inverse is not computed on demand. |
| 61 |
|
| 62 |
|
| 63 |
Values Must Be Hashable |
| 64 |
+++++++++++++++++++++++ |
| 65 |
|
| 66 |
Because you must be able to look up keys by value as well as values by key, |
| 67 |
values must also be hashable. |
| 68 |
|
| 69 |
Attempting to insert an unhashable value will result in an error: |
| 70 |
|
| 71 |
.. doctest:: |
| 72 |
|
| 73 |
>>> anagrams_by_alphagram = dict(opt=['opt', 'pot', 'top']) |
| 74 |
>>> bidict(anagrams_by_alphagram) |
| 75 |
Traceback (most recent call last): |
| 76 |
... |
| 77 |
TypeError: ... |
| 78 |
|
| 79 |
So in this example, |
| 80 |
using a tuple or a frozenset instead of a list would do the trick: |
| 81 |
|
| 82 |
.. doctest:: |
| 83 |
|
| 84 |
>>> bidict(opt=('opt', 'pot', 'top')) |
| 85 |
bidict({'opt': ('opt', 'pot', 'top')}) |
| 86 |
|
| 87 |
|
| 88 |
Values Must Be Unique |
| 89 |
+++++++++++++++++++++ |
| 90 |
|
| 91 |
As we know, |
| 92 |
in a bidirectional map, |
| 93 |
not only must keys be unique, |
| 94 |
but values must be unique as well. |
| 95 |
This has immediate implications for :mod:`bidict`'s API. |
| 96 |
|
| 97 |
Consider the following: |
| 98 |
|
| 99 |
.. doctest:: |
| 100 |
|
| 101 |
>>> b = bidict({'one': 1}) |
| 102 |
>>> b['two'] = 1 # doctest: +SKIP |
| 103 |
|
| 104 |
What should happen next? |
| 105 |
|
| 106 |
If the bidict allowed this to succeed, |
| 107 |
because of the uniqueness-of-values constraint, |
| 108 |
it would silently clobber the existing item, |
| 109 |
resulting in: |
| 110 |
|
| 111 |
.. doctest:: |
| 112 |
|
| 113 |
>>> b # doctest: +SKIP |
| 114 |
bidict({'two': 1}) |
| 115 |
|
| 116 |
This could result in surprises or problems down the line. |
| 117 |
|
| 118 |
Instead, bidict raises a |
| 119 |
:class:`~bidict.ValueDuplicationError` |
| 120 |
so you have an opportunity to catch this early |
| 121 |
and resolve the conflict before it causes problems later on: |
| 122 |
|
| 123 |
.. doctest:: |
| 124 |
|
| 125 |
>>> b['two'] = 1 |
| 126 |
Traceback (most recent call last): |
| 127 |
... |
| 128 |
bidict.ValueDuplicationError: 1 |
| 129 |
|
| 130 |
The purpose of this is to be more in line with the |
| 131 |
`Zen of Python <https://www.python.org/dev/peps/pep-0020/>`__, |
| 132 |
which advises, |
| 133 |
|
| 134 |
| *Errors should never pass silently.* |
| 135 |
| *Unless explicitly silenced.* |
| 136 |
|
| 137 |
So if you really just want to clobber any existing items, |
| 138 |
all you have to do is say so explicitly: |
| 139 |
|
| 140 |
.. doctest:: |
| 141 |
|
| 142 |
>>> b.forceput('two', 1) |
| 143 |
>>> b |
| 144 |
bidict({'two': 1}) |
| 145 |
|
| 146 |
Similarly, initializations and :meth:`~bidict.MutableBidict.update` calls |
| 147 |
that would overwrite the key of an existing value |
| 148 |
raise an exception too: |
| 149 |
|
| 150 |
.. doctest:: |
| 151 |
|
| 152 |
>>> bidict({'one': 1, 'uno': 1}) |
| 153 |
Traceback (most recent call last): |
| 154 |
... |
| 155 |
bidict.ValueDuplicationError: 1 |
| 156 |
|
| 157 |
>>> b = bidict({'one': 1}) |
| 158 |
>>> b.update({'uno': 1}) |
| 159 |
Traceback (most recent call last): |
| 160 |
... |
| 161 |
bidict.ValueDuplicationError: 1 |
| 162 |
|
| 163 |
>>> b |
| 164 |
bidict({'one': 1}) |
| 165 |
|
| 166 |
Setting an existing key to a new value |
| 167 |
does *not* cause an error, |
| 168 |
and is considered an intentional overwrite |
| 169 |
of the value associated with the existing key, |
| 170 |
in keeping with dict's behavior: |
| 171 |
|
| 172 |
.. doctest:: |
| 173 |
|
| 174 |
>>> b = bidict({'one': 1}) |
| 175 |
>>> b['one'] = 2 # succeeds |
| 176 |
>>> b |
| 177 |
bidict({'one': 2}) |
| 178 |
>>> b.update([('one', 3), ('one', 4), ('one', 5)]) |
| 179 |
>>> b |
| 180 |
bidict({'one': 5}) |
| 181 |
|
| 182 |
In summary, |
| 183 |
when attempting to insert an item whose key duplicates an existing item's, |
| 184 |
:class:`~bidict.bidict`'s default behavior is to allow the insertion, |
| 185 |
overwriting the existing item with the new one. |
| 186 |
When attempting to insert an item whose value duplicates an existing item's, |
| 187 |
:class:`~bidict.bidict`'s default behavior is to raise. |
| 188 |
This design naturally falls out of the behavior of Python's built-in dict, |
| 189 |
and protects against unexpected data loss. |
| 190 |
|
| 191 |
One set of alternatives to this behavior is provided by |
| 192 |
:meth:`~bidict.MutableBidict.forceput` |
| 193 |
(mentioned above) |
| 194 |
and :meth:`~bidict.MutableBidict.forceupdate`, |
| 195 |
which allow you to explicitly overwrite existing keys and values: |
| 196 |
|
| 197 |
.. doctest:: |
| 198 |
|
| 199 |
>>> b = bidict({'one': 1}) |
| 200 |
>>> b.forceput('two', 1) |
| 201 |
>>> b |
| 202 |
bidict({'two': 1}) |
| 203 |
|
| 204 |
>>> b.forceupdate([('three', 1), ('four', 1)]) |
| 205 |
>>> b |
| 206 |
bidict({'four': 1}) |
| 207 |
|
| 208 |
For even more control, |
| 209 |
you can use :meth:`~bidict.MutableBidict.put` |
| 210 |
and :meth:`~bidict.MutableBidict.putall`. |
| 211 |
These variants allow you to pass |
| 212 |
an :class:`~bidict.OnDup` instance |
| 213 |
to specify custom :class:`~bidict.OnDupAction`\s |
| 214 |
for each type of duplication that can occur. |
| 215 |
|
| 216 |
.. doctest:: |
| 217 |
|
| 218 |
>>> b = bidict({1: 'one'}) |
| 219 |
>>> b.put(1, 'uno', OnDup(key=RAISE)) |
| 220 |
Traceback (most recent call last): |
| 221 |
... |
| 222 |
bidict.KeyDuplicationError: 1 |
| 223 |
>>> b |
| 224 |
bidict({1: 'one'}) |
| 225 |
|
| 226 |
:mod:`bidict` provides the |
| 227 |
:attr:`~bidict.ON_DUP_DEFAULT`, |
| 228 |
:attr:`~bidict.ON_DUP_RAISE`, and |
| 229 |
:attr:`~bidict.ON_DUP_DROP_OLD` |
| 230 |
:class:`~bidict.OnDup` instances |
| 231 |
for convenience. |
| 232 |
|
| 233 |
If no *on_dup* argument is passed, |
| 234 |
:meth:`~bidict.MutableBidict.put` and |
| 235 |
:meth:`~bidict.MutableBidict.putall` |
| 236 |
will use :attr:`~bidict.ON_DUP_RAISE`, |
| 237 |
providing stricter-by-default alternatives to |
| 238 |
:meth:`~bidict.MutableBidict.__setitem__` |
| 239 |
and |
| 240 |
:meth:`~bidict.MutableBidict.update`. |
| 241 |
(These defaults complement the looser alternatives |
| 242 |
provided by :meth:`~bidict.MutableBidict.forceput` |
| 243 |
and :meth:`~bidict.MutableBidict.forceupdate`.) |
| 244 |
|
| 245 |
|
| 246 |
Key and Value Duplication |
| 247 |
+++++++++++++++++++++++++ |
| 248 |
|
| 249 |
Note that it's possible for a given item to duplicate |
| 250 |
the key of one existing item, |
| 251 |
and the value of another existing item. |
| 252 |
|
| 253 |
For example: |
| 254 |
|
| 255 |
.. code-block:: python |
| 256 |
|
| 257 |
b.putall([(1, -1), (2, -2), (1, -2)], on_dup=OnDup(...)) |
| 258 |
|
| 259 |
Here, the third item we're trying to insert, (1, -2), |
| 260 |
duplicates the key of the first item we're passing, (1, -1), |
| 261 |
and the value of the second item we're passing, (2, -2). |
| 262 |
|
| 263 |
Keep in mind, the :class:`~bidict.OnDup` |
| 264 |
may specify one :class:`~bidict.OnDupAction` |
| 265 |
for :attr:`key duplication <bidict.OnDup.key>` |
| 266 |
and a different :class:`~bidict.OnDupAction` |
| 267 |
for :attr:`value duplication <bidict.OnDup.val>`. |
| 268 |
|
| 269 |
In the case of a key and value duplication, |
| 270 |
the :class:`~bidict.OnDupAction` |
| 271 |
for :attr:`value duplication <bidict.OnDup.val>` |
| 272 |
takes precedence: |
| 273 |
|
| 274 |
.. doctest:: |
| 275 |
|
| 276 |
>>> on_dup = OnDup(key=DROP_OLD, val=RAISE) |
| 277 |
>>> b.putall([(1, -1), (2, -2), (1, -2)], on_dup=on_dup) |
| 278 |
Traceback (most recent call last): |
| 279 |
... |
| 280 |
bidict.KeyAndValueDuplicationError: (1, -2) |
| 281 |
|
| 282 |
Note that repeated insertions of the same item |
| 283 |
are construed as a no-op and will not raise, |
| 284 |
no matter what :class:`~bidict.OnDup` is: |
| 285 |
|
| 286 |
.. doctest:: |
| 287 |
|
| 288 |
>>> b = bidict({1: 'one'}) |
| 289 |
>>> b.put(1, 'one') # no-op, not a DuplicationError |
| 290 |
>>> b.putall([(2, 'two'), (2, 'two')]) # The repeat (2, 'two') is also a no-op. |
| 291 |
>>> b |
| 292 |
bidict({1: 'one', 2: 'two'}) |
| 293 |
|
| 294 |
See the :ref:`extending:\`\`YoloBidict\`\` Recipe` |
| 295 |
for another way to customize this behavior. |
| 296 |
|
| 297 |
|
| 298 |
Collapsing Overwrites |
| 299 |
+++++++++++++++++++++ |
| 300 |
|
| 301 |
When setting an item whose key duplicates that of an existing item, |
| 302 |
and whose value duplicates that of a *different* existing item, |
| 303 |
the existing item whose *value* is duplicated will be dropped, |
| 304 |
and the existing item whose *key* is duplicated |
| 305 |
will have its value overwritten in place: |
| 306 |
|
| 307 |
.. doctest:: |
| 308 |
|
| 309 |
>>> b = bidict({1: -1, 2: -2, 3: -3, 4: -4}) |
| 310 |
>>> b.forceput(2, -4) # item with duplicated value, namely (4, -4), is dropped |
| 311 |
>>> b # and the item with duplicated key, (2, -2), is updated in place: |
| 312 |
bidict({1: -1, 2: -4, 3: -3}) |
| 313 |
>>> # (2, -4) took the place of (2, -2), not (4, -4) |
| 314 |
|
| 315 |
>>> # Another example: |
| 316 |
>>> b = bidict({1: -1, 2: -2, 3: -3, 4: -4}) # as before |
| 317 |
>>> b.forceput(3, -1) |
| 318 |
>>> b |
| 319 |
bidict({2: -2, 3: -1, 4: -4}) |
| 320 |
>>> # (3, -1) took the place of (3, -3), not (1, -1) |
| 321 |
|
| 322 |
|
| 323 |
Updates Fail Clean |
| 324 |
++++++++++++++++++ |
| 325 |
|
| 326 |
If an update to a :class:`~bidict.bidict` fails, |
| 327 |
you can be sure that it fails clean. |
| 328 |
In other words, a :class:`~bidict.bidict` will never |
| 329 |
apply only part of an update that ultimately fails, |
| 330 |
without restoring itself to the state it was in |
| 331 |
before processing the update: |
| 332 |
|
| 333 |
.. doctest:: |
| 334 |
|
| 335 |
>>> b = bidict({1: 'one', 2: 'two'}) |
| 336 |
>>> b.putall({3: 'three', 1: 'uno'}) |
| 337 |
Traceback (most recent call last): |
| 338 |
... |
| 339 |
bidict.KeyDuplicationError: 1 |
| 340 |
|
| 341 |
>>> # (1, 'uno') was the problem... |
| 342 |
>>> b # ...but (3, 'three') was not added either: |
| 343 |
bidict({1: 'one', 2: 'two'}) |
| 344 |
|
| 345 |
This holds no matter why the update failed – |
| 346 |
not just for a :class:`~bidict.DuplicationError`, |
| 347 |
but also for e.g. an unhashable key or a malformed item. |
| 348 |
|
| 349 |
What is restored is the bidict's *contents*. |
| 350 |
For an :class:`~bidict.OrderedBidict`, |
| 351 |
the order of its items is restored as well. |
| 352 |
For other bidict types, it may not be: |
| 353 |
rolling back an overwrite reinserts the overwritten item, |
| 354 |
which puts it back at the end of the backing mapping |
| 355 |
rather than in its original position. |
| 356 |
So a failed update can leave a non-ordered bidict |
| 357 |
holding exactly the items it held before, |
| 358 |
but iterating them in a different order: |
| 359 |
|
| 360 |
.. doctest:: |
| 361 |
|
| 362 |
>>> b = bidict({1: 'one', 2: 'two'}) |
| 363 |
>>> b.update({1: 'uno', 3: 'two'}) # (1, 'uno') is applied, then (3, 'two') fails |
| 364 |
Traceback (most recent call last): |
| 365 |
... |
| 366 |
bidict.ValueDuplicationError: two |
| 367 |
|
| 368 |
>>> b # the contents are restored... |
| 369 |
bidict({1: 'one', 2: 'two'}) |
| 370 |
>>> b.inverse # ...but the inverse is no longer in its original order: |
| 371 |
bidict({'two': 2, 'one': 1}) |
| 372 |
|
| 373 |
This is the same caveat described in |
| 374 |
:ref:`other-bidict-types:Order consistency between bidicts and their inverses`, |
| 375 |
applied to updates that fail rather than updates that succeed: |
| 376 |
if you need a bidict whose order is meaningful, |
| 377 |
use an :class:`~bidict.OrderedBidict`. |
| 378 |
|
| 379 |
|
| 380 |
Order Matters |
| 381 |
+++++++++++++ |
| 382 |
|
| 383 |
Performing a bulk insert operation – |
| 384 |
i.e. passing multiple items to |
| 385 |
:meth:`~bidict.BidictBase.__init__`, |
| 386 |
:meth:`~bidict.MutableBidict.update`, |
| 387 |
:meth:`~bidict.MutableBidict.forceupdate`, |
| 388 |
or :meth:`~bidict.MutableBidict.putall` – |
| 389 |
is like inserting each of those items individually in sequence. |
| 390 |
[#fn-fail-clean]_ |
| 391 |
|
| 392 |
Therefore, the order of the items provided to the bulk insert operation |
| 393 |
is significant to the result. |
| 394 |
|
| 395 |
For example, let's try calling `~bidict.MutableBidict.forceupdate` |
| 396 |
with a list of three items that duplicate some keys and values |
| 397 |
already in an initial bidict: |
| 398 |
|
| 399 |
.. doctest:: |
| 400 |
|
| 401 |
>>> b = bidict({0: 0, 1: 2}) |
| 402 |
>>> b.forceupdate({ |
| 403 |
... 2: 0, # (2, 0) overwrites (0, 0) -> bidict({2: 0, 1: 2}) |
| 404 |
... 0: 1, # (0, 1) is added -> bidict({2: 0, 1: 2, 0: 1}) |
| 405 |
... 0: 0, # (0, 0) overwrites (0, 1) and (2, 0) -> bidict({1: 2, 0: 0}) |
| 406 |
... }) |
| 407 |
>>> b |
| 408 |
bidict({1: 2, 0: 0}) |
| 409 |
|
| 410 |
Now let's do the exact same thing, but with a different order |
| 411 |
of the items that we pass to :meth:`~bidict.MutableBidict.forceupdate`: |
| 412 |
|
| 413 |
.. doctest:: |
| 414 |
|
| 415 |
>>> b = bidict({0: 0, 1: 2}) # as above |
| 416 |
>>> b.forceupdate({ |
| 417 |
... # same items as above, different order: |
| 418 |
... 0: 1, # (0, 1) overwrites (0, 0) -> bidict({0: 1, 1: 2}) |
| 419 |
... 0: 0, # (0, 0) overwrites (0, 1) -> bidict({0: 0, 1: 2}) |
| 420 |
... 2: 0, # (2, 0) overwrites (0, 0) -> bidict({1: 2, 2: 0}) |
| 421 |
... }) |
| 422 |
>>> b # different items! |
| 423 |
bidict({1: 2, 2: 0}) |
| 424 |
|
| 425 |
Of course, if you try to initialize or update a bidict |
| 426 |
with an iterable that yields items in a nondeterministic order, |
| 427 |
the results will vary accordingly. |
| 428 |
|
| 429 |
.. [#fn-fail-clean] |
| 430 |
|
| 431 |
Albeit with the extremely important advantage of |
| 432 |
:ref:`failing clean <basic-usage:Updates Fail Clean>`. |
| 433 |
|
| 434 |
|
| 435 |
Interop |
| 436 |
+++++++ |
| 437 |
|
| 438 |
:class:`~bidict.bidict`\s interoperate well with other types of mappings. |
| 439 |
For example, they support efficient polymorphic equality testing: |
| 440 |
|
| 441 |
.. doctest:: |
| 442 |
|
| 443 |
>>> bidict(a=1) == dict(a=1) |
| 444 |
True |
| 445 |
|
| 446 |
And converting back and forth works as expected: |
| 447 |
|
| 448 |
.. doctest:: |
| 449 |
|
| 450 |
>>> dict(bidict(a=1)) |
| 451 |
{'a': 1} |
| 452 |
>>> bidict(dict(a=1)) |
| 453 |
bidict({'a': 1}) |
| 454 |
|
| 455 |
(Just remember that if there were any |
| 456 |
:ref:`duplicate values <basic-usage:Values Must Be Unique>` |
| 457 |
in the dict passed to :class:`~bidict.bidict`, |
| 458 |
it would trigger a :class:`~bidict.ValueDuplicationError`.) |
| 459 |
|
| 460 |
See the :ref:`other-bidict-types:Polymorphism` section |
| 461 |
for more interoperability documentation. |
| 462 |
|
| 463 |
---- |
| 464 |
|
| 465 |
Proceed to :doc:`other-bidict-types` |
| 466 |
for documentation on the remaining bidict variants. |