Preferred python typing syntax of Optional[Union] vs. Union[None] [closed]
Asked Answered
R

0

6

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?

Roxannroxanna answered 15/9, 2021 at 0:43 Comment(6)
They are isomorphic, but I would tend towards Optional if you wanted to stress that you didn't need to provide a value, but if you do, it's a str or an int. 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.Werner
The str,int example was maybe not the most apt, as it points to abusing the union type to define an interface that has more input parameter variations than what should be necessary. I will update this to be A, B to avoid diverting the attention of the issue.Roxannroxanna
I'm not really sure what changing the types to generic, hypothetical A/B changes with regards to what @Werner said...Dillon
Personally, I find the new PEP 604-style syntax much more readable and concise than either of these options, i.e. A | B | None. But I don't think there's any suggestion that Optional or Union 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-0604Cowl
I think it depends on the context, but I generally prefer Optional[...] in most cases where None 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" where None is a valid value it can take.Ellissa
The reasons for using Optional[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 widespread A | B | None would probably be the preferred variant. See https://mcmap.net/q/237970/-python-3-10-optional-type-or-type-none/320437Newel

© 2022 - 2024 — McMap. All rights reserved.