Can't narrow `Sequence[<X>]` to `Tuple[<X>, ...]` using `isinstance(..., tuple)`
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
Bug Report
Using isinstance(<Sequence[X]>, tuple) narrows the type of <Sequence[X]> to Tuple[Any, ...], not Tuple[X, ...] as one would expect.
To Reproduce
[mypy-play.net]
[pyright-play.net[^1]] (pyright handles this as expected)
from __future__ import annotations
from typing_extensions import (
assert_type,
Sequence,
Tuple,
)
value: Sequence[str]
if isinstance(value, tuple):
assert_type(value, Tuple[str, ...])
# expected: (this works)
# actual: "Expression is of type 'tuple[Any, ...]',
# not 'tuple[str, ....]'"
[^1]: the pyright example code is slightly modified (1) to avoid an error around value being uninitialized, and (2) to reflect that pyright behaves as expected
Expected Behavior
if instance(value, ...) should only ever narrow the type of value
Actual Behavior
Mypy narrows the container type, but forgets the element type
Your Environment
- Mypy version used: 1.8.0; bug exists back to at least 1.0
- Mypy command-line flags: (none)
- Mypy configuration options from
mypy.ini(and other config files): (none) - Python version used: 3.8, 3.12
Existing issues
While it seems extremely unlikely that this issue hasn't been reported, I haven't been able to locate anything obviously related among the ~217 issues that mention both isinstance and tuple. Issue #2456 may be vaguely related.
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
リンク先の mypy-play.net のケースの例を再現し、mypy が Sequence[str] に対して isinstance(value, tuple) をどのように絞り込むかを調べます。結果を assert_type の期待値およびリンク先の pyright の動作と比較します。絞り込まれた値が str 要素を Tuple[str, ...] として保持すれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- compilers
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 42/100