python / python/mypy

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

Open
#11,039 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

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

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 at visit_index_with_type and reproduce the provided MyEnum example with mypy, without the type: ignore comments. Check how enum detection handles a subclass with a customized getitem; done means the integer and slice accesses no longer produce the reported Enum index diagnostic while ordinary enum indexing remains handled correctly.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.