python / python/mypy

Unable to stubify Enum so it can be used with Literals, without using type ignore

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

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

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

説明

Bug Report

Extending the example for #3434 I want to define an enum Flag, combine some of the members, and then also reference those members as a TypeAlias in a stub file.

class Color1(Flag):
    RED = auto()
    BLUE = auto()
    GREEN = auto()
    WHITE = RED | BLUE | GREEN  # <-- This line works at runtime but not in a stub (see the gist)
# Invalid type: try using Literal[Color1.RED] instead
Favorites: TypeAlias = Literal[Color3.RED | Color3.BLUE]

(A clear and concise description of what the bug is.)

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.11&gist=d270d7541c61b2aea87e99c9afc77534

Expected Behavior

I expect mypy to suggest working code, or to accept the | operator for Flag members.

Actual Behavior

See the gist, but depending on how I write the stub I get these errors for the member definition

# foo.pyi:9: error: Invalid type: try using Literal[Color1.RED] instead?  [valid-type]
# foo.pyi:9: error: Invalid type: try using Literal[Color1.BLUE] instead?  [valid-type]
# foo.pyi:9: error: Invalid type: try using Literal[Color1.GREEN] instead?  [valid-type]

or these for the TypeAlias

# foo.pyi:12: error: Parameter 1 of Literal[...] cannot be of type "Any"  [valid-type]

Your Environment

  • Mypy version used: 1.5.1
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.10.13

I was curious what stubgen came up with:

from _typeshed import Incomplete
from enum import Flag
from typing import TypeAlias

class Color(Flag):
    RED: Incomplete
    BLUE: Incomplete
    GREEN: Incomplete
    WHITE: Incomplete

Favorites: TypeAlias

but that loses information about the Literal Favorite Colors.

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

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

はじめの一歩

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

調査の方向性

レポートにある mypy-play での再現例と foo.pyi の例から始め、Flag メンバーの定義と Literal TypeAlias に焦点を当てます。報告された valid-type エラーおよび Any エラーを、結合された Flag メンバーの想定される扱いと比較します。意図した stub が type ignores を必要とせずに literal の色情報を保持できれば完了です。

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

評価

技術スタック
python
領域
compilers
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

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

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