python / python/mypy

Do not raise "Enum index should be a string [misc]" for subclasses of Enum

Offen
#11,039 0 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

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

Beschreibung

Bug Report

The following was raised at https://stackoverflow.com/questions/68974940/how-to-suppress-index-should-be-a-string-type-error-on-subclassed-python-enum?noredirect=1#comment121902783_68974940

import enum

class MyEnumMeta(enum.EnumMeta):
  def __getitem__(self, indexOrSlice):
    if isinstance(indexOrSlice, (int, slice)):
      return list(self)[indexOrSlice]
    else:
      return enum.EnumMeta.__getitem__(self, indexOrSlice)

class MyEnum(enum.Enum, metaclass=MyEnumMeta): pass

class Period(MyEnum):
  A = "a"
  B = "b"
  C = "c"

print(Period["A"])
print(Period[1])    # type: ignore[misc]
print(Period[:2])   # type: ignore[misc]

The author of Python enum (PEP 435) responded that the # type: ignore[misc] should not be needed in this case because MyEnum is different from Enum

In other words, in visit_index_with_type, instead of checking with is_enum, please check whether the object really is an Enum (or at least check whether its __getitem__ differs from that of Enum)

To Reproduce

Apply mypy to the above code without the # type: ignore[misc]

Actual Behavior

mypy reports "Enum index should be a string" and blocks my commit

Your Environment

python 3.7.11

[mypy]
python_version = 3.7
warn_unused_configs = True
no_color_output = True
pretty = True
show_error_codes = True
disallow_subclassing_any = False

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 bei visit_index_with_type und reproduziere das bereitgestellte MyEnum-Beispiel mit mypy, ohne die Kommentare type: ignore. Prüfe, wie die Erkennung von Enum mit einer Unterklasse umgeht, die eine angepasste getitem-Methode hat; fertig ist die Änderung, wenn die Zugriffe auf Integer und Slices nicht mehr die gemeldete Enum-Index-Diagnose erzeugen, während gewöhnliche Enum-Indizierung weiterhin korrekt behandelt wird.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Bug
Schwierigkeit
3/5
Geschätzter Aufwand
1-2 Tage
Aktivitätsstatus
Veraltet
Klarheit
Klar beschrieben
Anfängerfreundlichkeit
42/100

Neue Issues direkt in Ihr Postfach

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