-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
False positive when mixing Mapping and Union #6001
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
This is because Mapping is invariant in its key type. See https://mypy.readthedocs.io/en/latest/common_issues.html#invariance-vs-covariance. |
I'm having a hard time understanding how this isn't a bug:
|
Mutability is not a root cause, the root cause is invariance. Mutable collections are typically invariant, but an immutable collection can be invariant as well. |
python/typing#273 discusses why Mapping's key type is invariant. |
What about items 1 and 2? How can invariance prevent |
|
FYI related discussion python/typing#445 and feature request python/typing_extensions#5 |
This is not type safe for the following reason:
In essence, because A way around this is: from typing import Any, Mapping, Union, TypeVar
StrVar = TypeVar("StrVar", bound=str)
StrOrIntVar = TypeVar("StrOrIntVar", bound=Union[str, int])
def f(arg: Mapping[ StrVar , Any]) -> None: pass
def g(arg: Mapping[StrOrIntVar, Any]) -> None: pass
f({'b': 'c'})
g({'b': 'c'})
d = {'b': 'c'}
f(d)
g(d) Using a Of course, in the particular case of |
A function that expects a heterogeneous dictionary and gets a dictionary with a subset of the expected types seems to cause problems.
Mypy's output is
I'm using Python 3.7.1 and Mypy 0.641. Possibly related to #5849?
The text was updated successfully, but these errors were encountered: