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?

frediy
  • 1,766
  • 15
  • 16
  • 2
    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. – chepner Sep 15 '21 at 00:57
  • 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. – frediy Sep 15 '21 at 01:37
  • I'm not really sure what changing the types to generic, hypothetical A/B changes with regards to what @chepner said... – juanpa.arrivillaga Sep 15 '21 at 01:43
  • 2
    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. https://www.python.org/dev/peps/pep-0604/ – Alex Waygood Sep 15 '21 at 08:58
  • 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. – Iguananaut Sep 15 '21 at 09:04
  • The reasons for using `Optional[Union[A, B]]` are mentioned in this nice answer: https://stackoverflow.com/a/51710151/320437 --- also when Python 3.10+ gets more widespread `A | B | None` would probably be the preferred variant. See https://stackoverflow.com/q/69440494/320437 – pabouk - Ukraine stay strong Nov 17 '21 at 17:51

0 Answers0