admin管理员组文章数量:1287624
Say I have a Python abstract class in the shape:
class AbcClass(ABC, Generic[T]): ...
With some implementations:
class IntClass(AbcClass[int]): ...
class StrClass(AbcClass[str]): ...
class FloatClass(AbcClass[float]): ...
Then I want to have a function foo
that takes in an instance of any of the subclasses and a value that matches the type of the generic of that subclass. For example:
def foo(obj: IntClass, value: int) -> None: ...
def foo(obj: StrClass, value: str) -> None: ...
def foo(obj: FloatClass, value: float) -> None: ...
I'm trying to create a decorator for foo
and want to correctly type the method signature. What's the right way to type the function foo
with a Callable? Right now I'm doing:
T = TypeVar("T", bound=AbcClass)
V = TypeVar("V")
FooFn = Callable[[T, V], None]
However, V
is not related to T
in the above code so even for a specific IntClass
technically V
could be any value. How can I fix this? Using the following is not possible since AbcClass
is not covariant and I want to be able to type any subclass (e.g.: IntClass
) as well.
FooFn = Callable[[AbcClass[V], V], None]
本文标签: Python generic TypeVar bound to generic base classStack Overflow
版权声明:本文标题:Python generic TypeVar bound to generic base class - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741305779a2371360.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论