Here is the situation I'm facing. I have class A and a generic type B. The type parameter of B bound to A.
from typing import Generic, TypeVar
AT = TypeVar("AT", bound="A")
BT = TypeVar("BT", bound="B")
class A:
pass
class B(Generic[AT]):
def __init__(self, a: AT):
self._a = a
def a(self) -> AT:
return self._a
I also have a generic class C with type parameter bounded by B. I want this class to have a method bar that given an object of type B returns something of the same type as the type parameter of the B passed as argument. I tried
class C(Generic[BT[AT]]):
def bar(self, b: BT) -> AT:
return b.a()
However, type checking on the code below with mypy gives:
Returning Any from function declared to return "AT"
I also tried:
class C(Generic[BT]):
def bar(self, b: BT[AT]) -> AT:
return b.a()
but then I get the error
Type variable "BT" used with arguments
Is there a way to capture this idea with type annotation or a better way to structure the code to capture this constraint?
Any idea about that? Thank you!