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]]
A Python optional argument is an argument with a default value. You can specify a default value for an argument using the assignment operator. There is no need to specify a value for an optional argument when you call a function.
Union type; Union[X, Y] is equivalent to X | Y and means either X or Y. To define a union, use e.g. Union[int, str] or the shorthand int | str . Using that shorthand is recommended.
The query parameter q is of type Union[str, None] (or str | None in Python 3.10), that means that it's of type str but could also be None , and indeed, the default value is None , so FastAPI will know it's not required. Note. FastAPI will know that the value of q is not required because of the default value = None .
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]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With