bidict/docs/caveat-equivalent-distinct-...

43 lines
1.1 KiB
PHP
Raw Normal View History

2018-01-03 18:16:37 +00:00
Equivalent but distinct :class:`~collections.abc.Hashable`\s
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Consider the following::
2018-01-03 18:16:37 +00:00
>>> d = {1: int, 1.0: float}
How many items do you expect *d* to contain?
2018-01-03 18:16:37 +00:00
The actual result might surprise you::
2018-01-03 18:16:37 +00:00
>>> len(d)
1
And similarly,
2018-01-03 18:16:37 +00:00
>>> dict([(1, int), (1.0, float), (1+0j, complex), (True, bool)])
{1: <... 'bool'>}
>>> 1.0 in {True}
True
(Note that ``1 == 1.0 == 1+0j == True``.)
This illustrates that a mapping cannot contain two items
with equivalent but distinct keys
(and likewise a set cannot contain two equivalent but distinct elements).
2018-01-03 18:16:37 +00:00
If an object that is being looked up in a set or mapping
is equal to a contained object,
the contained object will be found,
even if it is distinct.
With bidict,
since values function as keys in the inverse mapping,
2018-01-03 18:16:37 +00:00
this behavior occurs in the inverse direction too::
>>> from bidict import bidict
2018-01-03 18:16:37 +00:00
>>> b = bidict({1: 1.0})
>>> b.inv[True]
1
>>> b[2] = True
Traceback (most recent call last):
...
2018-01-03 18:16:37 +00:00
ValueDuplicationError: 1.0