简体   繁体   中英

Optional Union in type hint

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]]

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 ( Optional[T, U, None] ) is another monad, which however behaves differently than Optional and thus should not be named so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM