Type union in Dict key only passes when both types are used.
Apologies, not sure how best to describe this (see code perhaps). When a function parameter is annotated with a union type in a dict parameter's key type argument, it seems any argument provided needs to match exactly - it's not sufficient to match one or other of the types in the union. Is this expected?
Environment data
- Language Server version: 2022.3.2
- OS and version: darwin x64
- Python version (and distribution if applicable, e.g. Anaconda): Python 3.9.10 (pyenv)
- python.analysis.indexing: true
- python.analysis.typeCheckingMode: basic
Expected behaviour
from typing import Any, Dict, Union
def func(responses: Dict[Union[int, str], str]):
...
d0 = {"foo": "bar"}
d1 = {2: "qux"}
d2 = {"foo": "bar", 2: "qux"}
func(d0) # --> valid
func(d1) # --> valid
func(d2) # --> valid
Actual behaviour
from typing import Any, Dict, Union
def func(responses: Dict[Union[int, str], str]):
...
d0 = {"foo": "bar"}
d1 = {2: "qux"}
d2 = {"foo": "bar", 2: "qux"}
func(d0) # --> invalid A
func(d1) # --> invalid B
func(d2) # --> valid
Error A reported:
Argument of type "dict[str, str]" cannot be assigned to parameter "responses" of type "Dict[int | str, str]" in function "func"
TypeVar "_KT@dict" is invariant
Type "str" cannot be assigned to type "int | str"
"str" is incompatible with "int"
Error B reported:
Argument of type "dict[int, str]" cannot be assigned to parameter "responses" of type "Dict[int | str, str]" in function "func"
TypeVar "_KT@dict" is invariant
Type "int" cannot be assigned to type "int | str"
"int" is incompatible with "str"
This is the correct behavior. The type variables for the dict class are invariant, which means they need to match exactly. For details, refer to PEP 483 and 484. Also, refer to this documentation.
To make your sample work, you would need to provide type declarations rather than rely on type inference.
def func(responses: dict[int | str, str]):
...
d0: dict[int | str, str] = {"foo": "bar"}
d1: dict[int | str, str] = {2: "qux"}
d2 = {"foo": "bar", 2: "qux"}
func(d0) # --> valid
func(d1) # --> valid
func(d2) # --> valid
Thanks for confirming. I guess the other alternative is the func could union the actual dict types, rather than the key types, which would let the inference work as long as you were consistent about which key type you use each time.
def func(responses: Union[Dict[str, str], Dict[int, str]]):
...
d0 = {"foo": "bar"}
d1 = {2: "qux"}
d2 = {"foo": "bar", 2: "qux"}
func(d0) # --> valid
func(d1) # --> valid
func(d2) # --> invalid
FWIW This caught me using a part of fastapi that supports mapping responses for error codes as either strings or ints, so the above would make it easier as a consumer at the expense of a more verbose type declaration that excludes mixing the two (which is probably not their intent).