python / python/mypy

Narrowing enums causes `.value` to be typed as `Any`

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

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

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

説明

Bug Report

Apologies if this has already been reported, but I couldn't find an existing issue for it.

The issue I'm seeing is related to accessing the .value of an Enum after "narrowing" it with the is operator. It seems like the narrowing (to Union[Literal[...]]) works as expected, but then it fails to realize that the .value of all the variants have the same type (and so falls back to Any).

This only affects runs with --warn-return-any enabled:

$ mypy --config-file /dev/null --warn-return-any enum_narrowing.py

To Reproduce

It's probably easiest to see in this example:

import enum
from typing import Tuple

RGB = Tuple[int, int, int]

class Color(enum.Enum):
    WHITE = (255, 255, 255)
    BLACK = (0, 0, 0)

    def red(self) -> int:
        if self is Color.WHITE:
            return 255
        return self.value[0]  # error: Returning Any from function declared to return "int"

(playground URL: https://mypy-play.net/?mypy=latest&python=3.8&flags=warn-return-any&gist=b2a6df92fb37717e5c9d7542b6e88fec)

Expected Behavior

This should deduce that self.value has type RGB and succeed.

Actual Behavior

If I add some reveal_type(self) and reveal_type(self.value)s before/after the narrowing, I get this output:

enum_narrowing.py:11: note: Revealed type is "enum_narrowing.Color"
enum_narrowing.py:12: note: Revealed type is "Tuple[Literal[255]?, Literal[255]?, Literal[255]?]"
enum_narrowing.py:15: note: Revealed type is "Literal[enum_narrowing.Color.BLACK]"
enum_narrowing.py:16: note: Revealed type is "Any"

Your Environment

$ python --version
Python 3.8.0
$ mypy --version
mypy 0.991 (compiled: yes)

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

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

はじめの一歩

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

調査の方向性

まず、提供されている mypy コマンドを enum_narrowing.py に対して実行し、is による絞り込みの前後で明示された型を比較します。Enum メンバーの絞り込みと .value の型処理を追跡します。self.value[0] が int として推論され、--warn-return-any を付けて例が通れば修正は完了です。

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

評価

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

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

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