繁体   English   中英

Python3:类型提示,如何在定义 class 和通用 class 时使用 TypeVar

[英]Python3: Type Hint, How to use TypeVar while defining a class whithing a Generic class

我正在尝试在 Generic class 中使用TypeVar T:在_dataclass_helper

“值”中的 MyPy 错误

from typing import Generic, TypeVar
from dataclasses import dataclass


_T = TypeVar("_T")


class Base(Generic[_T]):
    @dataclass
    class _dataclass_helper:
        value: _T  #<<--- mypy: Type variable "HW.DC_ValueGeneric._T" is unbound 
        string: str

    def __init__(self):
        pass

    # using _dataclass_helper in the code

我试图将_dataclass_helper为 Generic,或者在 Base 的_dataclass_helper之外定义 _dataclass_helper ......但两者都错过了目标

让内部类继承Generic而不是外部类:

class Base:
    @dataclass
    class _dataclass_helper(Generic[_T]):
        value: _T
        string: str

    def __init__(self):
        pass

According to your comments, what you want is to determine the generics of internal classes while determining the generics of external classes, but the internal class and the external class are two independent classes, and there is no connection between them. 一种可能的选择是使用一种方法来构建内部类的实例:

_T = TypeVar("_T")
_S = TypeVar("_S")


class Base(Generic[_T]):

    @dataclass
    class _dataclass_helper(Generic[_S]):
        value: _S
        string: str

    def __init__(self):
        pass
    
    def helper(self, value: _T, string: str) -> _dataclass_helper[_T]:
        return self._dataclass_helper(value, string)

https://peps.python.org/pep-0484/#scoping-rules-for-type-variables中找到了答案

引用

嵌套在另一个通用 class 中的通用 class 不能使用相同类型的变量。 外部 class 的类型变量的 scope 不涵盖内部:

T = TypeVar('T')
S = TypeVar('S')

class Outer(Generic[T]):
    class Bad(Iterable[T]):       # Error
        ...
    class AlsoBad:
        x = None  # type: List[T] # Also an error

    class Inner(Iterable[S]):     # OK
        ...
    attr = None  # type: Inner[T] # Also OK

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM