Limited inference with union of callables and assignment to a union
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- PR マージ指標
- PR 指標を取得中
説明
Bug Report
Apologies if this was raised already. The only related issue I could find is https://github.com/python/mypy/issues/15887.
In Pydantic 2.10, we changed the definition of our field function to be:
from typing import Callable, TypeVar
_T = TypeVar('_T')
def Field(
*,
default_factory: Callable[[], _T] | Callable[[dict[str, Any]], _T],
) -> _T: ...
While this type checks correctly for some common use cases, we get errors when the Field function is assigned to a union of types, or when the default factory signature isn't trivial (e.g. contains overloads). Here are some examples failing:
EDIT: Seems like the issue was fixed since 1.16.0. The issue with Class.b remains:
cvar = ContextVar[None]("session_id", default=None)
class Class:
# error: Argument "default_factory" to "Field" has incompatible type "type[list[Any]]"; expected "Callable[[], Never] | Callable[[dict[str, Any]], Never]" [arg-type]:
a: list | None = Field(default_factory=list)
# error: Argument "default_factory" to "Field" has incompatible type overloaded function; expected "Callable[[], Never] | Callable[[dict[str, Any]], Never]" [arg-type]:
b: None = Field(default_factory=cvar.get) # note that `cvar.get` is overloaded. The first overload (`() -> None`) should match.
# fine:
fine: list = Field(default_factory=list)
Note that (at least for a), this worked as expected with the old type inference.
I first wanted to know if this can be considered a mypy limitation, or is the code really unsafe in some way? Or maybe is it because the typing spec does not provide any info regarding these use cases?
In comparison, pyright and pyre accepts the provided examples. We will currently recommend users to add a type: ignore comment and redirect to this issue. However, feel free to close if there's already an issue tracking this.
Thanks in advance
Your Environment
- Mypy version used: 1.13
- Mypy command-line flags: None
- Mypy configuration options from
mypy.ini(and other config files): None - Python version used: 3.13
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
提供された Python 3.13 の再現コードとリンクされた playground から始め、ContextVar.get がオーバーロードされて Field に渡される、残っている Class.b のケースに焦点を当てます。レポートで説明されている以前の推論と動作を比較し、その後、最初の () -> None オーバーロードが type: ignore なしで受け入れられることを示す回帰テストを追加します。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- devtools
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- おおむね明確
- 初心者へのやさしさ
- 45/100