Optional Union in type hint

Question:

In the type hint system, Optional[T] is said to be equivalent to Union[T, None]

Does this work for multiple type arguments? ie,

does Optional[T,U] break out to Union[T,U,None], or do I need to write it as Optional[Union[T,U]]

Asked By: flakes

||

Answers:

You may think of the typing library as a specification on how to declare certain types. If something is not defined in that specification then it’s always better assume it to be an undefined behavior.

However in the particular case of Python and typing we have a kind-of-reference static type checker which is mypy. So in order to get an answer for your question, or just programmatically check types, we may use it and see if it shows any warnings.

Here’s an example:

$ cat check_optional.py 
import typing
def fn(x: typing.Optional[int, str]):
    pass
$ mypy check_optional.py 
check_optional.py:3: error: Optional[...] must have exactly one type argument

So no, Optional[T, U] is not possible in terms of mypy even if there’s no trouble declaring it within the typing library.

Besides from "functional programming" perspective both Optional and Union are two distinct but well-known and well defined monads. A combination of two monads (Union[T, U, None]) is another monad, which however behaves differently than Optional and thus should not be named so. In other words, Union[T, U, None] is isomorphic to (=same as) Optional[Union[T, U]], but not to a general Optional[X].

Answered By: Vladimir
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.