isinstance check widens type
オープン
まだ誰も着手していません。
bug
topic-type-narrowing
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
- 2025-02-14: reproduced using mypy 1.15 and python 3.13 mypy-playground
- 2023-02-14: reproduced using mypy 1.0 and python 3.11 mypy-playground
from collections.abc import Collection, Mapping
def f(x: int | Collection[int] | Mapping[str, int]) -> int:
r"""Recursively sum up all the values of possibly nested data."""
if isinstance(x, int):
return x
if isinstance(x, Mapping):
return sum(f(y) for y in x.values())
reveal_type(x) # <- Here, mypy thinks this is Collection only!
if isinstance(x, Collection):
reveal_type(x) # <- Suddenly mypy thinks this is Collection | Mapping
return sum(f(y) for y in x) # ❌ "f" has incompatible type "int | str"
raise TypeError(f"unsupported type: {type(x)}")
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず、リンクされている mypy-playground の例で、記載された mypy および Python のバージョンを使って提供された reproducer を実行し、その後、Mapping 分岐の後で isinstance チェックが x をどのように絞り込むかを追跡します。Collection 分岐が一貫して x を絞り込み、示されている f の呼び出しが互換性のない int | str エラーなしで型チェックを通過すれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- compilers, devtools
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 35/100