python / python/mypy

Overloading a function with a parameter that can be either SomeType[Any] or Any always results in the return type Any

オープン
#10,752 コメント 9 件 リアクション 0 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

主要言語
Python
スター
20.6k
フォーク
3.3k
PR マージ指標
PR 指標を取得中

説明

Edit: I initially observed this behaviour for Callable[..., Any] and Any, but it now seems like this happens for any SomeType[Any] and Any, hence we've edited the title. For a more extensive explanation, scroll down to post 8.


I noticed that overloading a function with a Callable / Any parameter doesn't work as I'd expect. For example:

from typing import Any, Callable, overload

@overload
def foo(a: Callable) -> int: ...
@overload
def foo(a: Any) -> Any: ...

def foo(a):
    pass

a: str = foo(lambda x: x)

I'd expect the mypy error Incompatible types in assignment (expression has type "int", variable has type "str"), but there's no error here.

Of note, if I replace Callable by something else, it works fine:

from typing import Any, overload

@overload
def foo(a: int) -> int: ...
@overload
def foo(a: Any) -> Any: ...

def foo(a):
    pass

a: str = foo(1)
# mypy error: Incompatible types in assignment (expression has type "int", variable has type "str")

Finally, if I instead replace Any by something else, it also works fine.

from typing import Any, Callable, overload

@overload
def foo(a: Callable) -> int: ...
@overload
def foo(a: int) -> Any: ...

def foo(a):
    pass

a: str = foo(lambda x: x)
# mypy error: Incompatible types in assignment (expression has type "int", variable has type "str")

So it only doesn't work as expected in the first code block. Is that a bug? Or is it expected behaviour somehow?

コントリビューションガイド

コントリビューションガイドを開く

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

issue の overload 例から始め、mypy が SomeType[Any] のような overload と Any の overload のどちらを選択するかを追跡します。Callable/Any のケースを int/Any および Callable/int のケースと比較し、修正後の動作で互換性のない代入が報告される一方、既存の対照的なケースが維持されることを確認します。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
devtools
issue の種類
バグ
難易度
4/5
見積もり時間
3〜5日
活発さ
停滞
明瞭さ
おおむね明確
初心者へのやさしさ
35/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。