overload not working with Generic type
まだ誰も着手していません。
- 主要言語
- Python
- スター
- 20.6k
- フォーク
- 3.3k
- 平均マージ
- 1日 18時間
- マージ済み PR(30日)
- 54
説明
I'm running into an issue where a function overload is not working; I get no errors from mypy and one of the overload branches returns the proper type, but the other is returning Any instead of the type I would expect.
I've distilled it down to the snippet below. To reproduce, paste the following into a file and simply run mypy <filename>.
I'm running mypy version 0.770 on a Mac with homebrew Python 3.7.7
from typing import TypeVar, overload, Type, Optional, Generic
# Define a Player base class that can be paired with some data.
T = TypeVar('T')
class Player(Generic[T]):
pass
# Create an overloaded function to handle casting
# both Player and Optional[Player] to corresponding
# specific subtypes.
# (to ensure Optional state stays intact, unlike raw cast())
PT = TypeVar('PT', bound=Player)
@overload
def playercast(totype: Type[PT], obj: Player) -> PT:
...
@overload
def playercast(totype: Optional[Type[PT]],
obj: Optional[Player]) -> Optional[PT]:
...
def playercast(totype: Optional[Type[PT]],
obj: Optional[Player]) -> Optional[PT]:
return obj # type: ignore
# Now define a PlayerConcrete subtype, assign a few to Player vars,
# and then attempt to cast them back to PlayerConcrete.
class PlayerConcrete(Player[int]):
pass
player1: Optional[Player] = PlayerConcrete()
player2: Player = PlayerConcrete()
# Gives Optional[PlayerConcrete] as I would expect.
reveal_type(playercast(PlayerConcrete, player1))
# This, however, gives Any.
reveal_type(playercast(PlayerConcrete, player2))
# Doing the same thing with distinct functions works as expected.
def playercast_nonopt(totype: Type[PT], obj: Player) -> PT:
return obj # type: ignore
def playercast_opt(totype: Optional[Type[PT]],
obj: Optional[Player]) -> Optional[PT]:
return obj # type: ignore
# Gives Optional[PlayerConcrete].
reveal_type(playercast_opt(PlayerConcrete, player1))
# Gives PlayerConcrete.
reveal_type(playercast_nonopt(PlayerConcrete, player2))
Expected results:
- I would expect the second reveal_type() to return PT (ConcretePlayer in this case)
Actual results:
- The second reveal_type() returns Any
Should I expect this case to be functional? I've found that if Player is not a Generic class then it works. Is that a known limitation of overloads such as this, or is there a way to get this to work?
コントリビューションガイド
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
調査の方向性
まず、提供された Python スニペットを mypy 0.770 で実行し、2 つの reveal_type の結果を比較します。特に、汎用的な Player のオーバーロードを確認してください。PlayerConcrete の呼び出しに関係するオーバーロードと型推論の動作を追跡します。非オプショナルな呼び出しが Any ではなく PlayerConcrete を報告し、既存のオプショナルな動作が正しいままであれば完了です。
索引モデルが issue の本文から書いたものです。
評価
- 技術スタック
- python
- 領域
- devtools
- issue の種類
- バグ
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 活発さ
- 停滞
- 明瞭さ
- 明確に書かれている
- 初心者へのやさしさ
- 45/100