I have this code:
def my_foo(x: dict[str, int | float], some_condition: bool) -> None:
if some_condition:
x['the_int'] = 1
else:
x['the_float'] = 1.0
my_dict = {'some_int': 2}
my_foo(my_dict, True)
Mypy (understandably) complains
error: Argument 1 to "my_foo" has incompatible type "dict[str, int]"; expected "dict[str, int | float]" [arg-type] note: "Dict" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance src\type_test.py:23: note: Consider using "Mapping" instead, which is covariant in the value type
I tried do type-hint using MutableMapping but to no avail:
error: Argument 1 to "my_foo" has incompatible type "dict[str, int]"; expected "MutableMapping[str, int | float]"
my_dict: dict[str, int | float] = {'some_int': 2}. There should be a good dupe somewhere.int | floatis equivalent tofloat(you can pass an int anywhere a float is expected, just not vice versa) so you could simplify the annotation a bit by making itdict[str, float]. You do still need to explicitly annotatemy_dicteither way.