While troubleshooting a semi-related problem in the Python chat, I came upon some behavior in mypy that I don't understand.
from typing import Union, List, Dict
def f(x: Union[
Dict[str, float],
Dict[str, str],
Dict[str, int],
]):
pass
f({"a": 1}) #passes
f({"a": "b"}) #passes
f({"a": 1.0}) #passes
def g(x: Union[
Dict[str, float],
Dict[str, Union[str, int]],
]):
pass
g({"a": 1}) #fails
g({"a": "b"}) #fails
g({"a": 1.0}) #passes
def h(x: Dict[str, Union[float, str, int]]):
pass
h({"a": 1}) #passes
h({"a": "b"}) #passes
h({"a": 1.0}) #passes
When I execute mypy on this script, it only complains about the middle function, g:
C:\Users\Kevin\Desktop>mypy test.py
test.py:20: error: Argument 1 to "g" has incompatible type "Dict[str, int]"; expected "Union[Dict[str, float], Dict[str, Union[str, int]]]"
test.py:20: note: "Dict" is invariant -- see http://mypy.readthedocs.io/en/latest/common_issues.html#variance
test.py:20: note: Consider using "Mapping" instead, which is covariant in the value type
test.py:21: error: Argument 1 to "g" has incompatible type "Dict[str, str]"; expected "Union[Dict[str, float], Dict[str, Union[str, int]]]"
test.py:21: note: "Dict" is invariant -- see http://mypy.readthedocs.io/en/latest/common_issues.html#variance
test.py:21: note: Consider using "Mapping" instead, which is covariant in the value type
Found 2 errors in 1 file (checked 1 source file)
(As the notes imply, replacing Dict with Mapping removes the errors, but let's say for the sake of the question that I must use Dict.)
These errors are surprising to me. As far as I can tell, the type annotations for each function should simplify down to the same group of types: a dict whose keys are strings, and whose values are floats/strings/ints. So why does only g have incompatible types? Is mypy somehow confused by the presence of two Unions?