Union types

Python functions often accept values of two or more differenttypes. You can use overloading torepresent this, but union types are often more convenient.

Use the Union[T1, …, Tn] type constructor to construct a uniontype. For example, if an argument has type Union[int, str], bothintegers and strings are valid argument values.

You can use an isinstance() check to narrow down a union type to amore specific type:

  1. from typing import Union
  2.  
  3. def f(x: Union[int, str]) -> None:
  4. x + 1 # Error: str + int is not valid
  5. if isinstance(x, int):
  6. # Here type of x is int.
  7. x + 1 # OK
  8. else:
  9. # Here type of x is str.
  10. x + 'a' # OK
  11.  
  12. f(1) # OK
  13. f('x') # OK
  14. f(1.1) # Error

Note

Operations are valid for union types only if they are valid for _every_union item. This is why it’s often necessary to use an isinstance()check to first narrow down a union type to a non-union type. This alsomeans that it’s recommended to avoid union types as function return types,since the caller may have to use isinstance() before doing anythinginteresting with the value.