python / python/mypy

Support enum member `value` types

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

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

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

説明

Not sure if this would be in mypy or the typeshed, though it may need support in both.

Currently enum.IntEnum provides a way to have an enum whose value is an int, however all other enum.Enums have a .value of Any.

While this can be worked around in more recent versions of Python by adding a member without a value within the enum:

class MyEnum(str, enum.Enum):
    value: str
    FIRST = 'first'

This isn't ideal as it means that there are two places where this needs to be specified -- as an inherited type and within the class body.

It feels like it would be better if mypy was able to infer the member value type from the inheritance.

Aside: had generics existed before Enum, it feels like that might alternatively solved this, something like:

class MyEnum(enum.Enum[str]):
    FIRST = 'first'

Edit:
Note that this issue is about the general use-case of variables typed for the enum (such as x: MyEnum) -- mypy has long supported determining the type of specific members and their .values (e.g: reveal_type(MyEnum.FIRST.value) is already str or more recently Literal['first']).

I've put a more complete demo of this at https://gist.github.com/PeterJCLaw/d4334e498ab1391ee306886748e675f1.

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

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

はじめの一歩

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

調査の方向性

まず issue の完全なデモを確認し、mypy と typeshed における enum の処理を追跡します。issue では特定のファイルやテストは示されていません。enum 変数の値の型を継承からどのように推論すべきかを判断し、その後、一般的な enum インスタンスがクラス本体の個別のアノテーションなしで意図した値の型を公開することを示すカバレッジを追加します。

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

評価

技術スタック
python
領域
devtools
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
30/100

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

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