1 回答

TA貢獻1818條經驗 獲得超8個贊
理論上,您可以通過制作一個通用協議來完成他的一部分first,它可以讓您“捕獲” __add__. 例如:
# If you are using Python 3.7 or earlier, you'll need to pip-install
# the typing_extensions module and import Protocol from there.
from typing import TypeVar, Protocol, Generic
TOther = TypeVar('TOther', contravariant=True)
TSum = TypeVar('TSum', covariant=True)
class SupportsAdd(Protocol, Generic[TOther, TSum]):
def __add__(self, other: TOther) -> TSum: ...
然后,您可以執行以下操作:
S = TypeVar('S')
R = TypeVar('R')
# Due to how we defined the protocol, R will correspond to the
# return type of `__add__`.
def sum_two(first: SupportsAdd[S, R], second: S) -> R:
return first + second
# Type checks
reveal_type(sum_two("foo", "bar")) # Revealed type is str
reveal_type(sum_two(1, 2)) # Revealed type is int
reveal_type(sum_two(1.0, 2)) # Revealed type is float
# Does not type check, since float's __radd__ is ignored
sum_two(1, 2.0)
class Custom:
def __add__(self, x: int) -> int:
return x
# Type checks
reveal_type(sum_two(Custom(), 3)) # Revealed type is int
# Does not type check
reveal_type(sum_two(Custom(), "bad"))
但是,這種方法確實有一些限制:
它不處理
__add__
在“第一”中沒有匹配但__radd__
在“第二”中有匹配的情況。如果你修改自定義,你可能會得到一些奇怪的結果,所以這
__add__
是一個重載。我認為至少 mypy 目前有一個錯誤,它不知道如何正確處理涉及子類型和重載的復雜情況。
添加回答
舉報