Skip to content Skip to sidebar Skip to footer

Python 3 Types, Custom Variadic Generic Type With Arbitrary Number Of Contained Types, How?

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

Solution 1:

  • 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]]

Post a Comment for "Python 3 Types, Custom Variadic Generic Type With Arbitrary Number Of Contained Types, How?"