Skip to content

Support attribute access on enum members correctly #19422

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

sterliakov
Copy link
Collaborator

@sterliakov sterliakov commented Jul 11, 2025

Fixes #11368 (apparently canonical).
Fixes #10910.
Fixes #12107.
Fixes #13841.
Fixes #15186.
Fixes #15454.
Fixes #19418.

mypy now understands attribute access on enum members - the "recursive" behaviour of supporting access of almost-all enum members from members. "Almost", because .name and .value take precedence even if a member of the same name exists.

from enum import Enum

class E(Enum):
    FOO = 1
    BAR = 1

# The following is still a `E.BAR` instance:
E.FOO.FOO.BAR.BAR

Looks like this is a much wanted feature.

@@ -1971,8 +1972,8 @@ class B2(A2): # E: Cannot extend enum with existing members: "A2"
class A3(Enum):
x: Final[int] # type: ignore
class B3(A3):
x = 1 # E: Cannot override final attribute "x" (previously declared in base class "A3")

x = 1 # E: Cannot override final attribute "x" (previously declared in base class "A3") \
Copy link
Collaborator Author

@sterliakov sterliakov Jul 11, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that this (and other equivalent) change is correct: as per the spec, unannotated attrs should be interpreted as nonmembers, so, strictly speaking, you're assigning a soon-to-become enum instance to something of type int, breaking the interface. And it doesn't matter much as there is already another diagnostic on this line.

@sterliakov sterliakov marked this pull request as ready for review July 11, 2025 00:58
@sterliakov sterliakov requested a review from sobolevn July 11, 2025 00:58
Copy link
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

Copy link
Member

@sobolevn sobolevn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, looks reasonable! Not a full review, though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment