python / python/mypy

Type narrowing fails for union of iterable and dictionary when using `isinstance(x, Iterable)` in a conditional

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

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

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

説明

Bug Report

When using Union[Iterable[int], Dict[str, int]] together with isinstance(x, Iterable) in a conditional, the narrowing of the type does not work as expected. The previously correctly narrowed type is reverted to the un-narrowed type inside the branch.

To Reproduce

from typing import Dict, Iterable, Union


def test_iterable(x: Union[Iterable[int], Dict[str, int]]) -> Iterable[int]:
    if isinstance(x, dict):
        return [1, 2, 3]
    reveal_type(x)  # typing.Iterable[builtins.int]
    if isinstance(x, Iterable):
        reveal_type(x)  # Union[typing.Iterable[builtins.int], builtins.dict[builtins.str, builtins.int]]
        return x  # mypy falsely returns an error here

Expected Behavior

The type of x should be correctly narrowed down to Iterable[int].

Actual Behavior

Running mypy returns:

example.py:10: error: Incompatible return value type (got "Union[Iterable[int], Dict[str, int]]", expected "Iterable[int]")
Found 1 error in 1 file (checked 1 source file)

The problem persists even if the second if is changed to elif.

Your Environment

I used a clean virtual environment to test, only mypy was installed.

  • Mypy version used: 0.971
  • Python version used: 3.9.5

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

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

はじめの一歩

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

調査の方向性

example.py の reproducer から始め、それに対して mypy を実行して、union と isinstance チェックに関して報告されたエラーを確認します。ブランチが期待どおり Iterable[int] を報告するまで型の絞り込みの動作を追跡し、その後、互換性のない戻り値のエラーなしで例が完了することを確認します。

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

評価

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

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

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