5

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?

Ray
  • 7,833
  • 13
  • 57
  • 91

1 Answers1

-4
  • In your example, t is of type Thing, not Thing[str]. So this object accepts anything for T.
  • You can parametrize it like this : t2 = Thing[str]("WTF")
  • now, for your question, I think you want to use typing.Union like this: t3=Thing[Union[str,int,float]]("WTF")

By the way, you can check the type of generics by using get_generic_type() from typing_inspect

>>> get_generic_type(t)
__main__.Thing
>>> get_generic_type(t2)
__main__.Thing[str]
>>> get_generic_type(t3)
__main__.Thing[typing.Union[str, int, float]]
bct
  • 285
  • 2
  • 11