将类型的联合作为 TypeVar 的“绑定”参数并调用需要其中一种类型的重载函数,类型检查器报告错误
Giving Union of types as `bound` argument of TypeVar and calling overloaded function that requires one of the types, type checker reports an error
用mypy检查下面的代码,它说30: error: Argument 1 to "f" has incompatible type "T"; expected "X"
。
但是 f
有修饰声明,所以我们应该能够将 class X
或 Y
的值作为参数 a
传递。
问题 1:
我们不能同时使用 @overload 和 TypeVar(bound=Union) 吗?或者我误解了什么?
from typing import TypeVar, Union, overload
class X:
pass
class Y:
pass
@overload
def f(a: X):
...
@overload
def f(a: Y):
...
def f(a):
return
T = TypeVar("T", bound=Union[X, Y])
def func(a: T) -> T:
f(a)
return a
我尝试了另一个示例如下,它没有出现类型错误。
问题 2:重载函数和具有相同方法的 classes 有什么区别?
from typing import TypeVar, Union
class X:
def method(self) -> float:
return 1.0
class Y:
def method(self) -> float:
return 1.0
T = TypeVar("T", bound=Union[X, Y])
def func(a: T) -> T:
a.method()
return a
Question 1: Could not we use @overload and TypeVar(bound=Union) at the same time ? Or I misunderstand something ?
问题出在 TypeVar
:您想要的是 T = TypeVar("T", X, Y)
,因为 X
和 Y
都应该被接受。请参阅 documentation. The bound
parameter is used only if you want to define an upper bound to the types, basically you are specifying the constraining superclass. For more details, see Type variables with an upper bound 中的 用法 段落。
Question 2: What makes the difference between overloaded function and classes having same method ?
如果有两个 functions/methods 共享 相同范围 ,@overload
装饰器很有用,事实上
The variants and the implementations must be adjacent in the code: think of them as one indivisible unit.
用mypy检查下面的代码,它说30: error: Argument 1 to "f" has incompatible type "T"; expected "X"
。
但是 f
有修饰声明,所以我们应该能够将 class X
或 Y
的值作为参数 a
传递。
问题 1: 我们不能同时使用 @overload 和 TypeVar(bound=Union) 吗?或者我误解了什么?
from typing import TypeVar, Union, overload
class X:
pass
class Y:
pass
@overload
def f(a: X):
...
@overload
def f(a: Y):
...
def f(a):
return
T = TypeVar("T", bound=Union[X, Y])
def func(a: T) -> T:
f(a)
return a
我尝试了另一个示例如下,它没有出现类型错误。
问题 2:重载函数和具有相同方法的 classes 有什么区别?
from typing import TypeVar, Union
class X:
def method(self) -> float:
return 1.0
class Y:
def method(self) -> float:
return 1.0
T = TypeVar("T", bound=Union[X, Y])
def func(a: T) -> T:
a.method()
return a
Question 1: Could not we use @overload and TypeVar(bound=Union) at the same time ? Or I misunderstand something ?
问题出在 TypeVar
:您想要的是 T = TypeVar("T", X, Y)
,因为 X
和 Y
都应该被接受。请参阅 documentation. The bound
parameter is used only if you want to define an upper bound to the types, basically you are specifying the constraining superclass. For more details, see Type variables with an upper bound 中的 用法 段落。
Question 2: What makes the difference between overloaded function and classes having same method ?
如果有两个 functions/methods 共享 相同范围 ,@overload
装饰器很有用,事实上
The variants and the implementations must be adjacent in the code: think of them as one indivisible unit.