Home > database >  Python3: How to force different bound of generic TypeVar on inheritance
Python3: How to force different bound of generic TypeVar on inheritance

Time:04-03

Let's suppose following code;

from typing import Generic, TypeVar

class A1:
    x: int = 1

class A2(A1):
    y: int = -1

T = TypeVar("T", bound=A1)

class B1(Generic[T]):
    def __init__(self, a: T):
        self.a: T = a

class B2(B1):
    def __init__(self, a: T):
        self.a: T = a

I want to let user know that parameter(and state) a in B2.__init__ should be a subclass of A2, but it seems hard to found such way. The one possible way I found is following;

T2 = TypeVar("T2", bound=A2)

class B2(B1, Generic[T2]):
    def __init__(self, a: T2):
        self.a = a

But I don't know what happens to static type checkers if there are two Generic classes available. Which way is the most safe and elegant to resolve this situation?

I use Python 3.10.4.

CodePudding user response:

The B1 class lacks a type parameter in the B2 declaration. Adding T2 as a type parameter is correct, as A2 is a subclass of A1.

from typing import Generic, TypeVar


class A1:
    x: int = 1


class A2(A1):
    y: int = -1


T = TypeVar("T", bound=A1)
T2 = TypeVar("T2", bound=A2)


class B1(Generic[T]):
    def __init__(self, a: T):
        self.a: T = a


class B2(B1[T2]):
    def __init__(self, a: T2):
        self.a = a
  • Related