I want to create my own parameterized type in Python for use in type hinting:
# magic goes here
T = TypeVar('T')
assert MaybeWrapped[T] == Union[T, Tuple[T]]
If you're just trying to create generic classes or functions, try taking a look at the documentation on mypy-lang.org about generic types -- it's fairly comprehensive, and more detailed then the standard library typing docs.
If you're trying to implement your specific example, it's worth pointing out that type aliases work with typevars -- you can simply do:
from typing import Union, TypeVar, Tuple T = TypeVar('T') MaybeWrapped = Union[T, Tuple[T]] def foo(x: int) -> MaybeWrapped[str]: if x % 2 == 0: return "hi" else: return ("bye",) # When running mypy, the output of this line is: # test.py:13: error: Revealed type is 'Union[builtins.str, Tuple[builtins.str]]' reveal_type(foo(3))
However, if you're trying to construct a generic type with genuinely new semantics, you're very likely out of luck. Your remaining options are to: