As far as I can gather, the following two types are equivalent in Python:
Optional[Union[A, B]]
Union[A, B, None]
Is there a defined convention for which one to choose, such as a clause in PEP?
As far as I can gather, the following two types are equivalent in Python:
Optional[Union[A, B]]
Union[A, B, None]
Is there a defined convention for which one to choose, such as a clause in PEP?
© 2022 - 2024 — McMap. All rights reserved.
Optional
if you wanted to stress that you didn't need to provide a value, but if you do, it's astr
or anint
. The three-way union might make more sense for a return value. However, I would look at my interface to figure out if there's a way to redesign it to avoid the need for a union in the first place. Does your function accept a string only to try to convert it into an integer? Just require an integer, and let the caller handle the conversion. – WernerA | B | None
. But I don't think there's any suggestion thatOptional
orUnion
are to be deprecated any time soon, so you should certainly continue using them if and when you find they make your annotations more expressive. python.org/dev/peps/pep-0604 – CowlOptional[...]
in most cases whereNone
is a default value for an argument that may or may not be provided a non-trivial value. But there are also cases where an argument or variable might not be "optional" whereNone
is a valid value it can take. – EllissaOptional[Union[A, B]]
are mentioned in this nice answer: https://mcmap.net/q/86339/-how-should-i-use-the-optional-type-hint --- also when Python 3.10+ gets more widespreadA | B | None
would probably be the preferred variant. See https://mcmap.net/q/237970/-python-3-10-optional-type-or-type-none/320437 – Newel