Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Faulty type inference for Enum attributes #15454

Open
harahu opened this issue Jun 16, 2023 · 1 comment
Open

Faulty type inference for Enum attributes #15454

harahu opened this issue Jun 16, 2023 · 1 comment
Labels
bug mypy got something wrong topic-enum

Comments

@harahu
Copy link

harahu commented Jun 16, 2023

Bug Report

Accessing an instance of an enum though another instance leads to the wrong type being inferred for the instance.

To Reproduce

See: https://mypy-play.net/?mypy=master&python=3.12&flags=disallow-any-unimported&gist=26f57e606e831442885c45110b8d8650

import enum

class Color(enum.Enum):
    RED = "RED"
    GREEN = "GREEN"
    BLUE = "BLUE"

c = Color.RED

# error: Incompatible types in assignment (expression has type "str", variable has type "Color")  [assignment]
c = c.GREEN

Expected Behavior

I expect mypy to understand that c.GREEN is also of type Color.

Actual Behavior

Mypy thinks c.GREEN is of type str.

main.py:11: error: Incompatible types in assignment (expression has type "str", variable has type "Color")  [assignment]
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: master (post 1.3.0 at time of writing)
  • Mypy command-line flags: n/a
  • Mypy configuration options from mypy.ini (and other config files): n/a
  • Python version used: 3.12
@harahu harahu added the bug mypy got something wrong label Jun 16, 2023
@blbelew
Copy link

blbelew commented Jun 26, 2023

This is affecting me as well, but triggering a "Statement is unreachable" error when warn_unreachable = True is in my mypy.ini. Consider the following (using the previous color enum):

import enum

class Color(enum.Enum):
    RED = "RED"
    GREEN = "GREEN"
    BLUE = "BLUE"

def test(c:Color) -> str:
    if c == c.RED:
        return "it's red"
    if c == c.GREEN:
        return "it's green"
    if c == c.BLUE:
        return "it's blue"

    return "unknown color"

MyPy 1.3.0 doesn't complain about this code, but MyPy 1.4.0 gives "Statement is unreachable" errors for each of the three conditional returns.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-enum
Projects
None yet
Development

No branches or pull requests

3 participants