bidict/docs/namedbidict.rst.inc

38 lines
1.2 KiB
PHP
Raw Normal View History

:func:`~bidict.namedbidict`
---------------------------
2017-11-21 04:07:46 +00:00
:func:`bidict.namedbidict`,
2015-04-27 22:20:03 +00:00
inspired by :func:`collections.namedtuple`,
allows you to easily generate
2017-11-21 04:07:46 +00:00
a new bidirectional mapping type
with custom attribute-based access to forward and inverse mappings::
>>> from bidict import namedbidict
>>> ElementMap = namedbidict('ElementMap', 'symbol', 'name')
>>> noble_gases = ElementMap(He='helium')
>>> noble_gases.name_for['He']
'helium'
>>> noble_gases.symbol_for['helium']
'He'
>>> noble_gases.name_for['Ne'] = 'neon'
>>> del noble_gases.symbol_for['helium']
>>> noble_gases
ElementMap({'Ne': 'neon'})
Using the *base_type* keyword arg
whose default value is :class:`bidict.bidict`
you can override the bidict type used as the base class,
allowing the creation of e.g. a named frozenbidict type::
>>> from bidict import frozenbidict
>>> ElMap = namedbidict('ElMap', 'symbol', 'name', base_type=frozenbidict)
>>> noble = ElMap(He='helium')
>>> noble.symbol_for['helium']
'He'
2016-06-28 04:05:22 +00:00
>>> hash(noble) is not 'an error'
True
>>> noble['C'] = 'carbon' # mutation fails
Traceback (most recent call last):
...
TypeError: ...