-
-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Description
Bug Report
When sub-classing a Dict and overloading the keys
method the following error occurs when updating from mypy v0.921 to v0.930.
Return type "KeysView[_K]" of "keys" incompatible with return type "dict_keys[_K, _V]" in supertype "dict"
To Reproduce
With v0.291 this code is perfectly valid and passes validation.
from typing import TypeVar, Dict
from collections.abc import KeysView
_K = TypeVar("_K")
_V = TypeVar("_V")
class A(Dict[_K, _V]):
def __init__(self):
self._dict: Dict[_K, _V] = {}
def keys(self) -> KeysView[_K]:
return self._dict.keys()
https://mypy-play.net/?mypy=0.921&python=3.10&gist=7159c56ca6010a5aace637383a18b8b1
Post update to v0.930 the above code fails validation and requires updating to the following.
from typing import TypeVar, Dict
from _collections_abc import dict_keys
_K = TypeVar("_K")
_V = TypeVar("_V")
class A(Dict[_K, _V]):
def __init__(self):
self._dict: Dict[_K, _V] = {}
def keys(self) -> dict_keys[_K, _V]:
return self._dict.keys()
https://mypy-play.net/?mypy=latest&python=3.10&gist=65a7626023630e18d178acd0bd75ec61
Expected Behavior
The dict_keys
class extends the KeysView
class so I would have expected that the code could have remained the same and mypy would walk the hierarchy to determine that the code is still valid. For instance, this shows that the KeysView
should work (IMO) on v0.930
from collections.abc import KeysView
reveal_type({}.keys()) # Revealed type is "_collections_abc.dict_keys[<nothing>, <nothing>]"
print(isinstance({}.keys(), KeysView)) # True
Actual Behavior
The class must be rewritten to use the new dict_keys
return type which is not available in a "public" package.
Your Environment
- Mypy version used: v0.921 and v0.930
- Mypy command-line flags: N/A
- Mypy configuration options from
mypy.ini
(and other config files): N/A - Python version used: 3.6, 3.7, 3.8, 3.9, 3.10
- Operating system and version: Playground