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

Integer incorrectly narrowed to IntEnum #17860

Closed
JukkaL opened this issue Oct 1, 2024 · 0 comments · Fixed by #17866
Closed

Integer incorrectly narrowed to IntEnum #17860

JukkaL opened this issue Oct 1, 2024 · 0 comments · Fixed by #17866
Labels
bug mypy got something wrong topic-enum topic-type-narrowing Conditional type narrowing / binder

Comments

@JukkaL
Copy link
Collaborator

JukkaL commented Oct 1, 2024

The revealed narrowed type is unexpected, and there is a false negative:

from enum import IntEnum

class E(IntEnum):
    X = 1

def f(x: int) -> None:
    if x == E.X:
        print(x.value)  # No mypy error, but fails at runtime
        reveal_type(x)  # "Literal[E.X]"

f(1)

I'd expect the revealed type to be int, since that's the correct runtime type. IntEnum values are equal to the corresponding int objects:

print(1 == E.X)  # True

Also, x.value should be flagged as an error, since it fails at runtime.

If this needs special casing for IntEnums, it's fine. We already special case enums in various ways.

@JukkaL JukkaL added bug mypy got something wrong topic-enum topic-type-narrowing Conditional type narrowing / binder labels Oct 1, 2024
JukkaL added a commit that referenced this issue Oct 2, 2024
IntEnum/StrEnum values compare equal to the corresponding int/str values,
which breaks the logic we use for narrowing based on equality to a
literal value. Special case IntEnum/StrEnum to avoid the incorrect
behavior.

Fix #17860.
@JukkaL JukkaL closed this as completed in aa7733a Oct 2, 2024
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 topic-type-narrowing Conditional type narrowing / binder
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant