Optional typing for more than a single type

Question:

Since the documentation only uses Optional with a single type (Optional[X]), I was wondering if Union is required if I have an argument that accepts either a string, a list, or None.

def func(
    arg: Optional[str, list]
)
def func(
    arg: Optional[Union[str, list]]
)
Asked By: birdx0810

||

Answers:

Edit: I first wrote this, but this is incorrect:

"Since Optional[...] is shorthand for Union[..., None], they are essentially the same, and you can just use Optional[str, list], since that’s the same as Union[str, list, None]."

In fact, Python currently only accepts a single argument for Optional[X].

So, your valid options are:

def func(
    arg: Optional[Union[str, list]]
)

def func(
    arg: Union[str, list, None]
)

def func(
    arg: Union[str, list] | None
)

Some type checkers do seem to accept the Optional[str, list], but using it will cause an exception at runtime:

TypeError: typing.Optional requires a single type. Got (<class 'str'>, <class 'list'>).
Answered By: Grismar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.