Python TypeVar with abstract class implementation

31 views Asked by At

I have an abstract class that defines functions that need to be implemented by subclasses

P = TypeVar('P', int, List[int])

class Abstract(metaclass=ABCMeta):
    
    @abstractmethod
    def process(self, key: int) -> P:
        pass


class Test(Abstract):
    def __init__(self):
       ...
    
    def process(self, key: int) -> P:
        ...

The abstract function process can return either a int or List[int]. When creating instances of Test I want to set a specific type for a instance to be either int or List[int] in its process function implementation, something like

t1 = Test[int]()
t2 = Test[List[int]]()

which when calling process would then return the specific type

res: int = t1.process(1)  # returns an int
res: List[int] = t2.process(1)  # returns a List[int]

How/where would I have to specify the types to accomplish that restriction?

0

There are 0 answers