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

Joshua Bronson report at bugs.python.org
Fri Dec 31 14:35:56 EST 2021


Joshua Bronson <jabronson at gmail.com> added the comment:

Dear Raymond,

Thanks so much for the detailed response!

I wonder if you could explain how this case is different from the following:

>>> c = collections.ChainMap({1: 1}, {1: 2})
>>> iter(c)
<dict_keyiterator object at ...>
>>> isinstance(c, dict)  # it's fine, we <3 duck typing!
False


Now suppose a new .mapping attribute were added to dict_keyiterator objects in a future version of Python, like the one that was added to dict view objects in Python 3.10. Then, wouldn't ChainMap find itself in a similar predicament as this issue is raising?

>>> iter(c).mapping
mappingproxy({1: None})


As in my example above, the {1: None} mapping here is an implementation detail of ChainMap.__iter__() that was never intended to be leaked to users. (Ref: <https://github.com/python/cpython/blob/e18d815/Lib/collections/__init__.py#L998-L1002>)

Note also that ChainMap.__iter__() returns a dict_keyiterator object even though issubclass(ChainMap, dict) is False. We consider this just fine though, because the dict_keyiterator object currently behaves exactly like the generator object we would get if the code had done a `yield from d` rather than a `return iter(d)`. Except for being faster.

This parallels the implementations of bidict.keys()/values()/items(), which currently return dict_keys/dict_values/dict_items objects generated from internal data, that behave exactly like KeysViews(b)/ValuesView(b)/ItemsView(b) would*, except for being faster. And, as this issue is raising, except for this new .mapping attribute in Python 3.10+ now leaking internal state.

* I even have the passing property-based tests to prove it: <https://github.com/jab/bidict/pull/217/files#diff-995af13b14fe897c5d200fa97ed88fad03e401b2fc0cc167624d482ea512ba96R431-R459> :)


(I also have counterpoints for your other feedback, but wanted to post this part first. And sorry for my delay in responding – hope it's not too late! And finally thanks so much again for considering this and for the time you took to give feedback on bidict – there's literally no better-qualified person in the world. I so appreciate it!)

----------

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


More information about the Python-bugs-list mailing list