为什么这个类型提示不起作用
from typing import Generic, TypeVar
from dataclasses import dataclass
V = TypeVar('V', int, str)
@dataclass
class Test(Generic[V]):
a: V
class Base(Generic[V]):
def test(self) -> Test[V]:
t = '1'
return Test[V](t)
b = Base[str]()
b.test()
mypy
显示
test.py:16: error: Argument 1 to "Test" has incompatible type "str"; expected "int" [arg-type]
我的期望是创建具有指定类型
Base
的实例str
,它用于V
,当它转换为test()
时,它应该在
Test[str](t)
返回值中兼容
我的期望是创建具有指定类型
的实例Base
,它用于str
,当它转换为V
test()
时,它应该在Test[str](t)
返回值中兼容
您的
b = Base[str]()
行对 class Base(Generic[V]):
的定义没有任何追溯作用 - Base.test
的定义只是未通过类型检查,因为 t
是 str
(通过 t = '1'
),所以返回的是什么是 Test[str]
而不是通用 Test[V]
- 它不是返回“混合”类型的方法(请参阅 typing.AnyStr
作为示例,那里的文档对此有讨论)。将该分配更改为 t = 1
和 b = Base[int]()
,mypy 会抱怨相反的情况:
error: Argument 1 to "Test" has incompatible type "int"; expected "str" [arg-type]
使用
pyright
实际上会给出更好的错误消息:
/tmp/so_78174062.py:16:24 - error: Argument of type "Literal['1']"
cannot be assigned to parameter "a" of type "V@Base" in function "__init__"
Type "Literal['1']" cannot be assigned to type "V@Base" (reportArgumentType)
这清楚地强调了这是两种不同的类型,而测试方法真正应该具有此签名:
def test(self) -> Test[str]:
t = '1'
return Test[str](t)
以上将正确键入检查。