Python 3.10 (use |
): Example for a function which takes a single argument that is either an int
or str
and returns either an int
or str
:
def func(arg: int | str) -> int | str:
^^^^^^^^^ ^^^^^^^^^
type of arg return type
Python 3.5 - 3.9 (use typing.Union
):
from typing import Union
def func(arg: Union[int, str]) -> Union[int, str]:
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
type of arg return type
For the special case of X | None
you can use Optional[X]
.