泛型参数中递归类型的类型提示

问题描述 投票:0回答:0

我有一个稍微复杂的类型情况,我能想到的最小可复制版本看起来像这样:

from __future__ import annotations

from typing import TypeVar

T = TypeVar("T")


class MyClass(list[T]):
    def method(self, num: int) -> MyClass[MyRecursiveType]:
        if num == 1:
            return MyClass([1, 2, 3])

        return MyClass([*self, 1, 2, 3])


MyRecursiveType = int | MyClass["MyRecursiveType"]

我的想法是 MyClass.method(...) 应该返回 MyClass 的一个实例,并且它应该包含 int 或更多的 MyClass 实例(因此是递归类型)

问题是,如果我运行 mypy,我会在 L13 上收到错误消息:

error: List item 0 has incompatible type "MyClass[T]";预期“联盟[int,MyClass [MyRecursiveType]]”[列表项]

我可以让 mypy 停止抱怨,方法是将我的

T
添加到
MyRecursiveType
的联合中,并将其明确标记为
TypeAlias
,如下所示:

from __future__ import annotations

from typing import TypeAlias, TypeVar

T = TypeVar("T")


class MyClass(list[T]):
    def method(self, num: int) -> MyClass[MyRecursiveType]:
        if num == 1:
            return MyClass([1, 2, 3])

        return MyClass([*self, 1, 2, 3])


MyRecursiveType: TypeAlias = int | T | MyClass["MyRecursiveType"]

但这感觉不太正确,更正确的解决方案是什么?

python python-3.x type-hinting mypy
© www.soinside.com 2019 - 2024. All rights reserved.