The class typing.Tuple
can be used as with arbitrary number of type arguments, like Tuple[int, str, MyClass]
or Tuple[str, float]
. How do I implement my own class that can be used like that? I understand how to inherit from typing.Generic
. The following code demonstrates this.
from typing import TypeVar, Generic
T = TypeVar("T")
class Thing(Generic[T]):
def __init__(self, value: T):
self.value = value
def f(thing: Thing[int]):
print(thing.value)
if __name__ == '__main__':
t = Thing("WTF")
f(t)
The above code would work but the type checker (in my case PyCharm) would catch the fact that t
should be of type Thing[int]
and not Thing[str]
. That's all fine, but how do I make the class Thing
support arbitrary number of type arguments, like Tuple
does?