Passing a python generic to parent class?

Viewed 223

I have a parent class which is declared as a generic, an abstract subclass and a concrete implementation of that subclass, which declares the generic type:

MyType = TypeVar('MyType')

class A(Generic[MyType]):
   a: MyType

class B(Generic[MyType], A[MyType]):
   pass

class C(B[int]):
   pass

But this doesn't forward the generic declaration from C to A, so the type of a is not int. Is there a correct way to do this? Tried searching both SO and python docs but could not find anything.

1 Answers

On A you have a class variable, so it is shared amongst all instances of the class. If you try and type hint this you have a conflict anytime you create a new sub-class of A.

For instance what type does a have here:

class A(Generic[MyType]):
   a: MyType

class A1(A[str]):
   pass

class A2(A[int]):
   pass

If you want to represent a member variable on A then you can do it like this:

class A(Generic[MyType]):
    def __init__(self, a: MyType):
        self.val = a


class B(Generic[MyType], A[MyType]):
    def __init__(self, b: MyType):
        A.__init__(self, b)


class C(B[int]):
    def __init__(self, c: int):
        B.__init__(self, c)


class D(B[str]):
    def __init__(self, d: str):
        B.__init__(self, d)

Here we have two classes C and D which both have different generics intandstr` and the type hinting works because we are creating sub-classes which have different generics on them.

Hope after 6 months this might help :)

Related