Skip to content

Mapping with Union for keys #8477

Description

@RobertoPrevato

Hi,
Considering the following example:

fromtypingimport*defexample(value: Mapping[Union[str, int], Union[str, int]]):
...
x: Mapping[str, int] = {
"a": 1,
"b": 2,
"c": 3
}
example(x) # <-- MyPy doesn't like this: Argument 1 to "example" has incompatible type "Mapping[str, int]"; expected "Mapping[Union[str, int], Union[str, int]]"mypy(error)

Results in error: Argument 1 to "example" has incompatible type "Mapping[str, int]"; expected "Mapping[Union[str, int], Union[str, int]]"mypy(error).

Shouldn't MyPy accept the Mapping[str, int] to be a valid instance of Mapping[Union[str, int], Union[str, int]]?

This behavior looks surprising, because Union is supported for values, but not for keys. If the function annotation is modified this way:

fromtypingimport*defexample(value: Union[Mapping[str, Union[str, int]],
Mapping[int, Union[str, int]]]):
...
x: Mapping[str, int] = {
"a": 1,
"b": 2,
"c": 3
}
example(x)

Then mypy is happy. Version: mypy==0.761

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions