Python 泛型:无法分配给声明类型“T@func”
我正在尝试将通用键入介绍给我的功能,但是正在遇到一个钢铁错误:
Expression of type "A" cannot be assigned to declared type "T@func"
Type "A" cannot be assigned to type "T@func"
我在代码中的问题将问题减少到了这个简化的版本:
from typing import TypeVar, Union, List
class A:
def __init__(self, arg: str) -> None:
self.arg = arg
class B:
def __init__(self, arg: int) -> None:
self.arg = arg
T = TypeVar("T", A, B)
def getA() -> A:
return A("a")
def getB() -> B:
return B(1)
def func(arg: T) -> T:
out: T
if isinstance(arg, A):
out = getA()
elif isinstance(arg, B):
out = getB()
return out
print(func(A("a")))
错误发生在两个 out = geta()
out = getB()
Pyright无法在此处准确推断类型吗?我是犯错吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您将
t
绑定到func
通过arg
bunc 时,您说的是t
是arg arg
,您将自己知道的东西分配给的类型/代码>在
func
中。当您声明out
为t
时,您说的是out
始终与arg arg
的类型相同。因此,通过将geta
的结果调节到a
,但是out
必须是b
如果arg
是b
。为避免类型错误,您只需写
func
像这样:在您的条件下,您实际上将
arg
的类型范围缩小到 a 和b
,因此,如果您在条件中返回,则知道您正在返回t
,即与arg arg
相同的类型。When you bind
T
tofunc
viaarg
, you are sayingT
is the type ofarg
infunc
. When you declareout
as aT
, you are sayingout
will always be the same type asarg
. So by assinging the result ofgetA
toout
, you are assigning something you know is anA
to aT
, butout
must be aB
ifarg
is aB
.To avoid the type errors, you can just write
func
like this:Within your conditions, you actually have narrowed the type of
arg
toA
andB
, so if you return inside the conditions, you know you are returning aT
, i.e. the same type asarg
.