mypy:如何在通用类中声明返回自我的返回类型?
这个答案似乎对仿制药不起作用。 Mypy在选中以下代码时抱怨“错误:丢失通用类型A的类型参数”。我尝试使用'a [t]'
为TypeVar使用,但Mypy说“错误:类型变量t是未结合的”。我还尝试使用anya [t]
作为get
的返回类型,但这会产生两个错误消息,即已知的“错误:丢失通用类型A的类型参数”新的错误消息“与参数一起使用的变量Anya类型”。
如何正确指定get
的返回类型?
import typing
T = typing.TypeVar('T')
AnyA = typing.TypeVar('AnyA', bound='A')
class A(typing.Generic[T]):
def __init__(self, val: T) -> None:
self.val = val
def get(self: AnyA) -> AnyA:
return self
class B(A[T]):
def is_int(self) -> bool:
return isinstance(self.val, int)
if __name__ == '__main__':
b = B(42)
print(b.get().is_int())
This answer does not seem to work for generics. Mypy complains about "error: Missing type parameters for generic type A" when checking the following code. I have tried using 'A[T]'
for the TypeVar but then mypy says "error: Type variable T is unbound." I have also tried using AnyA[T]
as return type of get
but that produces two error messages, the already known "error: Missing type parameters for generic type A" and the new error message "Type variable AnyA used with arguments".
How do I specify the return type of get
correctly?
import typing
T = typing.TypeVar('T')
AnyA = typing.TypeVar('AnyA', bound='A')
class A(typing.Generic[T]):
def __init__(self, val: T) -> None:
self.val = val
def get(self: AnyA) -> AnyA:
return self
class B(A[T]):
def is_int(self) -> bool:
return isinstance(self.val, int)
if __name__ == '__main__':
b = B(42)
print(b.get().is_int())
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我知道在这里键入的三种方法:
声明内部自我型
这种方法在
mypy
文档中描述,请参见替代构造函数的精确键入。但是请注意,这是
mypy
- 特定的东西,可能无法与其他检查器一起使用。例如pyre
尚不支持内部自我类型。使用
_Typeshed.Self
这保存了声明的自定义类型的样板,但需要从Typeshed中导入一些晦涩的导入,而在运行时会失败。因此,它必须由
typing.type_checking
:_typeshed.Self
创建以首先在自定义存根中使用,但也适用于内联键入。python 3.11及向上:
typing.self
最近引入的 pep 673 将
self
添加到stdlib,因此从python 3.11开始,一个人将能够使用:mypy
现在不支持这一点,但是到目前为止来自版本1.1.184的Pyright 。I know of three ways of typing here:
Declaring an inner self-type
This approach is described in
mypy
docs, see Precise typing of alternative constructors.Note however, that this is
mypy
-specific stuff and may not work with other checkers. E.g.pyre
doesn't support inner self-types yet.Using
_typeshed.Self
This saves the boilerplate of declaring custom types, but requires a somewhat obscure import from typeshed which will fail at runtime. It thus must be wrapped by
typing.TYPE_CHECKING
:_typeshed.Self
was created to be used in custom stubs in the first place, but is suitable for inline typing as well.Python 3.11 and upwards:
typing.Self
A recently introduced PEP 673 adds
Self
to stdlib, so starting from Python 3.11 one will be able to use that:This is not supported by
mypy
yet as of now though, but e.g. bypyright
from version 1.1.184.