`TypeIs` narrowing of union type in a generic is not working
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
Bug Report
Given an object of type int | bytes and a TypeIs function that narrows int | str | bytes into int | str, mypy correctly infers that the original object is really just int.
However, this doesn't work if the union is a generic parameter. That is, given Sequence[int | bytes] and a narrowing function from Sequence[int | str | bytes] to Sequence[int | str], mypy doesn't infer that the original is Sequence[int]. Instead, it infers that the original is Sequence[int | str].
I think this is a bug? But of course I might just be holding it wrong. Any help will be greatly appreciated.
To Reproduce
from typing import Callable, TypeIs, Sequence, assert_type
def check_plain(value: int | str | bytes) -> TypeIs[int | str]:
return isinstance(value, int | str)
def check_sequence(seq: Sequence[int | str | bytes]) -> TypeIs[Sequence[int | str]]:
return all(isinstance(value, int | str) for value in seq)
def works(value: int | bytes) -> None:
assert check_plain(value)
assert_type(value, int)
def doesnt(value: Sequence[int | bytes]) -> None:
assert check_sequence(value)
assert_type(value, Sequence[int])
https://mypy-play.net/?mypy=1.19.0&python=3.13&gist=100053f110206f3fdf37170ea75a3ca2
Actual Behavior
main.py:15: error: Expression is of type "Sequence[int | str]", not "Sequence[int]" [assert-type]
Found 1 error in 1 file (checked 1 source file)
Your Environment
- Mypy version used: 1.19.0
- Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files): None - Python version used: 3.13
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず、提供された再現コードを mypy 1.19.0 で実行し、汎用的な Sequence のケースで失敗する assert_type を確認します。ジェネリックパラメーターに対する TypeIs の narrowing ロジックを追跡します。完了条件は、報告されたエラーなしに例で value が Sequence[int] に絞り込まれ、一方で単純なケースが引き続き動作することです。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- devtools
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 38/100