[issue45670] New .mapping attribute is broken for some existing uses of dict views

Raymond Hettinger report at bugs.python.org
Sun Oct 31 15:46:24 EDT 2021


Raymond Hettinger <raymond.hettinger at gmail.com> added the comment:

Sorry, but this isn't bug in Python.  The documented and supported API is the MappingView ABC where the _mapping attribute is private.

As an optimization, the bidict project has elected to forgo the supported API and instead use a concrete implementation designed specifically for actual dictionaries.  This is an unsupported use and the constructor is not a public API.

We don't even do this internally in the standard library. OrderedDict, for example, has its own odict_keys() type for the C version and _OrderedDictKeysView() for the pure python version.

It would be possible for us to add a set_mapping() method or make the attribute writeable but that would send us down the path for having to support non-dicts throughout and would tie our hands with respect to implementation techniques that rely on the mapping being an actual dictionary.  That isn't worth it for a code optimization and it loses the benefits arising from separate concrete and abstract classes.

Likewise, I don't think a documentation update makes sense because we don't document a constructor, so there is no documented way for a user to get into this position.

For the bidict project, several options come to mind:

1) To continue down the path of using dict_keys, dict_values, and dict_items, consider building a subclass that hides the mapping attribute or that raises a NotImplementedError. That is what collections.Counter() does with the inherited fromkeys() classmethod.

2) Build a C or Cython extension to implement an optimized concrete implementation designed specifically for bidict. That is what collections.OrderedDict() does for keys, values, and items.

3) Forgo the optimization and use the supported MappingView ABC.  That is what collections.ChainMap() does.

4) Just document that *mapping* behaves differently in bidict.

Thank you for the clear bug report with examples. It made it easier to drill into what was happening.

----------
assignee:  -> rhettinger
resolution:  -> not a bug
stage:  -> resolved
status: open -> closed

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue45670>
_______________________________________


More information about the Python-bugs-list mailing list