TypeVar:参数类型,作为bound参数的值

nme*_*nme 5 python generics typing mypy

我想实现这样的通用类:

S = TypeVar("S")
T = TypeVar("T", bound=OtherParametrizedClass)

class MyClass(Generic[T[S]]):
    def some_method(param: S) -> None:
        pass
Run Code Online (Sandbox Code Playgroud)

我已经尝试了以下方法:

S = TypeVar("S")
T = TypeVar("T", bound=OtherParametrizedClass)

class MyClass(Generic[S, T[S]]):
    def some_method(param: S) -> None:
        pass
    def other_method(param: T) -> None:
        pass
Run Code Online (Sandbox Code Playgroud)

MyPy可以正常使用。但是,当Python解释器运行此代码时,它给我以下错误:

TypeError: 'TypeVar' object is not subscriptable.
Run Code Online (Sandbox Code Playgroud)

正如我所发现的,这意味着TypeVar没有[]实现任何运算符。

是否有人对如何获得同时满足mypy和Python解释器的解决方案有想法?

编辑:我也尝试了以下方法:

S = TypeVar("S")
T = TypeVar("T", bound=OtherParametrizedClass[S])

class MyClass(Generic[T]):
    def some_method(param: S) -> None:
        pass
    def other_method(param: T) -> None:
        pass
Run Code Online (Sandbox Code Playgroud)

Python解释器不会给出任何错误/警告。但是,mypy抱怨第二行:

Invalid type "S"
Run Code Online (Sandbox Code Playgroud)

Gio*_*eri -2

我不确定我是否完全理解您想要实现的目标。

基本上有两个问题:

  • 为什么需要定义T
  • 为什么是MyClass Generic[T]而不是Generic[S]

第二个问题是关键:我认为从根本上来说,你犯的错误是你试图创建MyClass Generic[T],而它应该只是Generic[S],此时你甚至不需要定义Tother_method就可以返回了OtherParametrizedClass[S]

下面是我认为可以实现您想要实现的目标的示例:

import dataclasses
from typing import Generic, TypeVar

N = TypeVar("N", int, float)


@dataclasses.dataclass
class Adder(Generic[N]):
    to_add: N

    def add(self, value: N) -> N:
        return value + self.to_add


class Foo(Generic[N]):
    def get_adder(self, to_add: N) -> Adder[N]:
        return Adder(to_add)
Run Code Online (Sandbox Code Playgroud)

从我的示例到您的示例的名称映射:

  • NS
  • AdderOtherParametrizedClass
  • FooMyClass
  • Foo.get_adderMyClass.other_method