python / python/mypy

Enum .name property has str type

Open
#18,786 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-enum
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report
I stumbled across a weird issue with literals and using the .name property with enums. I was wondering if this is expected behavior. Seems inconsistent to me.

To Reproduce

from enum import Enum
from typing import Literal


class Foo(Enum):
    A = 1
    B = 1


keys = Literal["A", "B", "C"]


def f(name: keys) -> None:
    print(name)


foo: Foo = Foo.A

f(foo.name) # Error: Argument 1 to "f" has incompatible type "str"; expected "Literal['A', 'B', 'C']"
f(Foo.A.name) # No Error

Expected Behavior

I would expect both versions to be valid.

Your Environment

  • Mypy version used: mypy 1.15.0 (compiled: yes)
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.11.11

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the issue's minimal Python 3.11 reproducer with mypy 1.15.0 and compare the inferred types of foo.name and Foo.A.name. Trace the enum and Literal handling involved in those expressions, then add coverage for the reported calls and verify that the behavior matches the agreed expectation.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.