bidict/docs/polymorphism.rst.inc

33 lines
895 B
PHP
Raw Normal View History

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,
which is a better way to check for interface conformance::
>>> from collections import Mapping, MutableMapping
>>> isinstance(bidict(), Mapping)
True
>>> isinstance(bidict(), MutableMapping)
True
Though you can often write more polymorphic code
by using duck typing rather than :func:`isinstance`::
>>> # LBYL-style:
>>> if hasattr(foo, '__setitem__'): # doctest: +SKIP
... foo['bar'] = 'baz'
2016-06-28 04:05:22 +00:00
>>> # EAFP-style:
>>> try: # doctest: +SKIP
... foo['bar'] = 'baz'
2016-06-28 04:05:22 +00:00
... except TypeError:
... # plan B