python / python/mypy

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

オープン
#11,039 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

bug topic-enum topic-metaclasses
主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

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

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

visit_index_with_type から始め、提供されている MyEnum の例を、type: ignore コメントなしで mypy を使って再現します。カスタマイズされた getitem を持つサブクラスを Enum の検出がどのように処理するかを確認します。整数およびスライスによるアクセスで、報告されている Enum インデックス診断が生成されなくなり、通常の Enum のインデックスアクセスは引き続き正しく処理されれば完了です。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
devtools
issue の種類
バグ
難易度
3/5
見積もり時間
1〜2日
活発さ
停滞
明瞭さ
明確に書かれている
初心者へのやさしさ
42/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。