Union type narrowing behaves differently depending on argument position
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
Bug Report
In the following example the type narrowing of the union types works as expected if it appears in the first or second argument position, but breaks if it appears in position three (or later).
This issue probably falls into the topic-join-v-union.
To Reproduce
Example on mypy playground
from typing import Callable, TypeVar
T = TypeVar("T")
def func(
a: Callable[[], T],
b: Callable[[], T],
c: Callable[[], T],
) -> T:
raise NotImplementedError()
class Foo:
...
class Bar:
...
def make_foo() -> Foo:
raise NotImplementedError()
def make_bar() -> Bar:
raise NotImplementedError()
def make_foo_or_bar() -> Foo | Bar:
raise NotImplementedError()
x1: Foo | Bar = func(a=make_foo_or_bar, b=make_foo, c=make_bar)
x2: Foo | Bar = func(a=make_foo, b=make_foo_or_bar, c=make_bar)
x3: Foo | Bar = func(a=make_foo, b=make_bar, c=make_foo_or_bar)
Expected Behavior
The example should type check properly.
Actual Behavior
Inferring the return type works properly for x1 and x2, but it fails for x3 with:
Incompatible types in assignment (expression has type "object", variable has type "Foo | Bar") [assignment]
Considering that the code is fully valid and symmetric, there should not be a difference in the behavior.
Side note: The issue cannot be work-around at call site by just swapping the order of a and c in the func(...) call. Apparently it has to do with the order in which they appear in the function signature.
Your Environment
- Mypy version used: 1.6.1
- Mypy command-line flags: none
- Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.10, 3.11
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
Issue の再現コードから始め、mypy 1.6.1 または現行バージョンに対して実行して、位置による違いを確認します。func の callable 引数の型推論を追跡し、3 番目のパラメーターが object になる理由を調査します。x1、x2、x3 のすべてで一貫して型チェックが通れば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- devtools
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- 明確に書かれている
- 初心者へのやさしさ
- 35/100