2016-06-28 04:05:22 +00:00
|
|
|
.. _polymorphism:
|
|
|
|
|
|
|
|
Polymorphism
|
|
|
|
------------
|
|
|
|
|
|
|
|
Note that none of the bidict types inherit from dict::
|
|
|
|
|
|
|
|
>>> from bidict import bidict
|
|
|
|
>>> isinstance(bidict(), dict)
|
|
|
|
False
|
|
|
|
|
|
|
|
If you must use :func:`isinstance` to check whether a bidict is dict-like,
|
|
|
|
you can use the abstract base classes from the :mod:`collections` module,
|
2017-11-20 03:24:08 +00:00
|
|
|
which is the proper way to check if an object is a mapping::
|
2016-06-28 04:05:22 +00:00
|
|
|
|
|
|
|
>>> from collections import Mapping, MutableMapping
|
|
|
|
>>> isinstance(bidict(), Mapping)
|
|
|
|
True
|
|
|
|
>>> isinstance(bidict(), MutableMapping)
|
|
|
|
True
|
|
|
|
|
2017-11-20 03:24:08 +00:00
|
|
|
Of course you can also use duck typing to avoid :func:`isinstance` altogether::
|
2016-06-28 04:05:22 +00:00
|
|
|
|
|
|
|
>>> # EAFP-style:
|
|
|
|
>>> try: # doctest: +SKIP
|
squashed changes for 0.13.0
- support Python 3.6, refactor CI/test setup, increase test coverage
- refactor BidirectionalMapping, BidictBase, OrderedBidictBase,
FrozenBidictBase, and subclasses
- move frozenorderedbidict into _frozen and looseorderedbidict into _loose
- register bidict as a virtual subclass of MutableMapping rather than
inheriting from it directly. This makes it clearer that it does not use any
of the concrete generic methods that MutableMapping provides.
- improve performance and flexibility of frozenbidict and
frozenorderedbidict hashing
- docs, including new type-hierarchy.png diagram
- rm unused imap, ifilter, izip_longest from compat, add PYPY
- update to latest versions of dependencies
- restore benchmarking on travis
2017-01-09 15:37:31 +00:00
|
|
|
... foo['bar'] = 'baz'
|
2016-06-28 04:05:22 +00:00
|
|
|
... except TypeError:
|
|
|
|
... # plan B
|
2017-11-20 03:24:08 +00:00
|
|
|
|
|
|
|
>>> # LBYL-style:
|
|
|
|
>>> if hasattr(foo, '__setitem__'): # doctest: +SKIP
|
|
|
|
... foo['bar'] = 'baz'
|
|
|
|
|
|
|
|
Also note that since
|
|
|
|
:class:`bidict <bidict.bidict>` extends
|
|
|
|
:class:`frozenbidict <bidict.frozenbidict>`,
|
|
|
|
if you need to check whether a bidict is immutable,
|
|
|
|
testing for ``isinstance(foo, frozenbidict)``
|
|
|
|
is not what you want::
|
|
|
|
|
|
|
|
>>> from bidict import frozenbidict
|
|
|
|
>>> isinstance(bidict(), frozenbidict)
|
|
|
|
True
|
|
|
|
|
|
|
|
Instead you can check for
|
|
|
|
``isinstance(foo, Hashable)`` or
|
|
|
|
``isinstance(foo, MutableMapping)`` to get the desired behavior::
|
|
|
|
|
|
|
|
>>> from collections import Hashable
|
|
|
|
>>> isinstance(frozenbidict(), Hashable)
|
|
|
|
True
|
|
|
|
>>> isinstance(bidict(), Hashable)
|
|
|
|
False
|
|
|
|
>>> isinstance(bidict(), MutableMapping)
|
|
|
|
True
|
|
|
|
>>> isinstance(frozenbidict(), MutableMapping)
|
|
|
|
False
|