Skip to content

Make name and value read-only for Enums #6576

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

Merged
merged 2 commits into from
Dec 13, 2021

Conversation

AlexWaygood
Copy link
Member

These attributes are read-only properties at runtime; they should be read-only properties in the stub, also.

The following snippet currently fails at runtime, but passes mypy:

from enum import Enum

class Menu(Enum):
    SPAM = 1
    HAM = 2

Colours = Enum('Colours', 'RED YELLOW BLUE')

Menu.SPAM.name = 'BACON'
Menu.HAM.value = 4
Colours.RED.name = 'PURPLE'
Colours.YELLOW.value = 5

With this proposed patch applied, mypy yields the following true-positive errors for the above snippet:

test_enum.py:9: error: Property "name" defined in "Enum" is read-only
test_enum.py:10: error: Property "value" defined in "Enum" is read-only
test_enum.py:11: error: Property "name" defined in "Enum" is read-only
test_enum.py:12: error: Property "value" defined in "Enum" is read-only

@AlexWaygood
Copy link
Member Author

The Enum class does some magic to ensure that the name and value properties result in AttributeErrors if you try to access them directly from the class, rather than from a member of the class. I suspect that's what is throwing off stubtest. They exist, I promise!

@github-actions

This comment has been minimized.

1 similar comment
@github-actions
Copy link
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

ignite (https://github.com/pytorch/ignite)
+ ignite/engine/events.py:141: error: unused "type: ignore" comment

steam.py (https://github.com/Gobot1234/steam.py)
+ steam/enums.py:188: error: Definition of "name" in base class "Enum" is incompatible with definition in base class "Enum"  [misc]

@srittau srittau merged commit 0f2e87e into python:master Dec 13, 2021
@AlexWaygood
Copy link
Member Author

AlexWaygood commented Dec 13, 2021

A follow-up PR is required -- I didn't realise that name and value are overriden in the stub for IntEnum and Flag! I'll get on it now.

@AlexWaygood
Copy link
Member Author

A follow-up PR is required -- I didn't realise that name and value are overriden in the stub for IntEnum and Flag! I'll get on it now.

#6578 is the follow-up.

1 similar comment
@AlexWaygood
Copy link
Member Author

A follow-up PR is required -- I didn't realise that name and value are overriden in the stub for IntEnum and Flag! I'll get on it now.

#6578 is the follow-up.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants