mypy:如何在通用类中声明返回自我的返回类型?

发布于 2025-01-31 11:46:38 字数 797 浏览 1 评论 0原文

这个答案似乎对仿制药不起作用。 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

奈何桥上唱咆哮 2025-02-07 11:46:38

我知道在这里键入的三种方法:

声明内部自我型

这种方法在mypy文档中描述,请参见替代构造函数的精确键入

class A(typing.Generic[T]):
    _Self = typing.TypeVar('_Self', bound='A[T]')

    def __init__(self, val: T) -> None:
        self.val = val

    def get(self: _Self) -> _Self:
        return self

但是请注意,这是mypy - 特定的东西,可能无法与其他检查器一起使用。例如pyre尚不支持内部自我类型。

使用_Typeshed.Self

这保存了声明的自定义类型的样板,但需要从Typeshed中导入一些晦涩的导入,而在运行时会失败。因此,它必须由typing.type_checking

from typing import Any, TYPE_CHECKING

if TYPE_CHECKING:
    from _typeshed import Self
else:
    Self = Any

class A(typing.Generic[T]):
    def __init__(self, val: T) -> None:
        self.val = val

    def get(self: Self) -> Self:
        return self

_typeshed.Self创建以首先在自定义存根中使用,但也适用于内联键入。

python 3.11及向上:typing.self

最近引入的 pep 673 self添加到stdlib,因此从python 3.11开始,一个人将能够使用:

from typing import Self

class A(typing.Generic[T]):
    def __init__(self, val: T) -> None:
        self.val = val

    def get(self: Self) -> Self:
        return self

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.

class A(typing.Generic[T]):
    _Self = typing.TypeVar('_Self', bound='A[T]')

    def __init__(self, val: T) -> None:
        self.val = val

    def get(self: _Self) -> _Self:
        return self

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:

from typing import Any, TYPE_CHECKING

if TYPE_CHECKING:
    from _typeshed import Self
else:
    Self = Any

class A(typing.Generic[T]):
    def __init__(self, val: T) -> None:
        self.val = val

    def get(self: Self) -> Self:
        return self

_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:

from typing import Self

class A(typing.Generic[T]):
    def __init__(self, val: T) -> None:
        self.val = val

    def get(self: Self) -> Self:
        return self

This is not supported by mypy yet as of now though, but e.g. by pyright from version 1.1.184.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文