python / python/mypy

mypy cannot determine Enum members from static or Final values

Offen
#17,187 3 Kommentare 2 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug Report
To Reproduce

Here are 3 variations on creating IntEnum or StrEnum using functional API syntax.

testing1.py: (Success)

UpperSeat = IntEnum("UpperSeat", {"Seat1": 1, "Seat2": 2, "Seat3": 3})

testing2.py: (Error)

UPPER_CODES: Final[dict[str, int]] = {"Seat1": 1, "Seat2": 2, "Seat3": 3}
UpperSeat = IntEnum("UpperSeat", UPPER_CODES)

testing3.py: (Error)

UPPER_CODES: Final[dict[str, int]] = {f"Seat{code}": code for code in range(1, 3)}
UpperSeat = IntEnum("UpperSeat", UPPER_CODES)

Expected Behavior

All three of these produce valid Python code, but only one of these passes mypy type analysis.
I would argue that UPPER_CODES in both testing2 and testing3 are static.
In testing2.py, UPPER_CODES is a static constant.
In testing3.py, UPPER_CODES is provably static.
In both testing2 and testing3, Final values are used, so mypy should not be throwing this error.

Actual Behavior

testing1.py - Uses static values in-line: mypy yields Success
testing2.py and testing3.py: mypy yields Error:

main.py:8: error: Second argument of IntEnum() must be string, tuple, list or dict literal for mypy to determine Enum members  [misc]
main.py:9: error: Second argument of StrEnum() must be string, tuple, list or dict literal for mypy to determine Enum members  [misc]
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: 1.10.0
  • Mypy command-line flags: n/a
  • Mypy configuration options from mypy.ini (and other config files): n/a
  • Python version used: python 3.12

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne damit, die drei Fälle in testing1.py, testing2.py und testing3.py mit mypy 1.10.0 zu reproduzieren, und verfolge anschließend die funktionale IntEnum- und StrEnum-Analyse, die ein Literal-Mapping erfordert. Füge Regressionstests für Mappings mit Final-Werten hinzu, einschließlich des Comprehension-Falls, und bestätige, dass mypy die Enum-Mitglieder fehlerfrei ableitet.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
30/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.