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:
- from typing import Union
- def f(x: Union[int, str]) -> None:
- x + 1 # Error: str + int is not valid
- if isinstance(x, int):
- # Here type of x is int.
- x + 1 # OK
- else:
- # Here type of x is str.
- x + 'a' # OK
- f(1) # OK
- f('x') # OK
- 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.