1

When using the typing module to write type hints, I'm not sure when and when not I am supposed to use TypeVar instances.

For example, what's the practical "difference" between

str_or_int = typing.TypeVar('str_or_int', str, int)

and

str_or_int = typing.Union[str, int]

used in a hint like this?

def foo(bar: str_or_int):
    pass
actual_panda
  • 1,178
  • 9
  • 27

1 Answers1

2
T = TypeVar('T', str, int)

def foo(bar: T) -> T:
    pass

This is how typevars are used. This means bar could be either a str or int and foo will return a value of the same type as bar was. You won't get that with a Union:

str_or_int = Union[str, int]

def foo(bar: str_or_int) -> str_or_int:
    pass

This just means that bar can be a str or int and that foo will return a str or int, there's no connection between the type of bar and the return value.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • Thanks! In cases where this difference does not matter (such as the `foo` in my OP), what's the preferred class to use? – actual_panda Mar 19 '20 at 09:12
  • With `TypeVar` you're always establishing a connection. It's a *variable name* in your type system. Don't use it unless that's what you want, or you may see unexpected side effects. – deceze Mar 19 '20 at 09:19