Skip to content

Mypy inferring Union[str, str] when using enum.value inside dict.get #12523

Closed as not planned
@patrick91

Description

@patrick91

Hi folks, I was updating Mypy and I discovered this (potential) bug, basically running mypy on this code:

from enum import Enum


class Example(str, Enum):
    ACCOUNT = "account"
    ACCOUNT_2 = "account_2"
    
    def t(self) -> None:
        print(example_map.get(self.value))


example_map = {
    Example.ACCOUNT: 1,
    Example.ACCOUNT_2: 2,
}

triggers this error:

# print(example_map.get(self.value))
No overload variant of "get" of "Mapping" matches argument type "Union[str, str]"

This if fixed by doing:

print(example_map.get(self))

or by changing the map to

example_map = {
    Example.ACCOUNT.value: 1,
    Example.ACCOUNT_2.value: 2,
}

Is this behaviour expected? I'm asking because we have a lot of code that uses that pattern and changing it will require a lot of time. All the examples I've posted work in python

Playground URL: https://mypy-play.net/?mypy=latest&python=3.10&gist=d16680b7aa62a2f37ab09788432e9fa9

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions