[issue46399] Addition of `mapping` attribute to dict views classes has inadvertently broken type-checkers

Inada Naoki report at bugs.python.org
Wed Jan 19 04:48:22 EST 2022


Inada Naoki <songofacandy at gmail.com> added the comment:

> I agree with Inada that not every internal type should be exposed, but I would make an exception for the dict views classes due to the fact that dict subclasses are much more common than subclasses of other mappings, such as OrderedDict. I don't think it's *particularly* important to expose the OrderedDict views classes in the same way.

I am afraid that you misread me. I used OrderedDict as one example of dict subclass. I didn't mean dict_(keys|items|values) shouldn't exposed because of I don't want to expose odict_(keys|items|values).

Anyway, OrderedDict was not good choise to explain my thought because its builtin type and defined in typeshed. Instead, I use sortedcontainers.SortedDict as example.

See https://github.com/grantjenks/python-sortedcontainers/blob/dff7ef79a21b3f3ceb6a19868f302f0a680aa243/sortedcontainers/sorteddict.py#L43

It is a dict subclass. It's `keys()` method returns `SortedKeysView`.
`SortedKeysView` is subclass of `collections.abc.KeysView`. But it is not subclass of `dict_keys`.
If `dict.keys()` in typeshed defines it returns `dict_keys`, doesn't mypy flag it as an "incompatible override"?

So I propose that typeshed defines that dict.keys() returns KeysView, not dict_keys.

Although subclass of dict is very common, it is very rare that:

* Override `keys()`, and
* Returns `super().keys()`, instead of KeysView (or list), and
* `.keys().mapping` is accessed.

It is very minor inconvinience that user need to ignore false positive for this very specific cases.
Or do you think this case is much more common than classes like SortedDict?

Note that dict_(keys|items|values) is implementation detail and subclassing it doesn't make sense.

Another option is adding more ABC or Protocol that defines `.mapping` attribute.
SortedKeysView can inherit it and implement `.mapping`.

----------

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


More information about the Python-bugs-list mailing list