As the title says, it would be convenient to represent a union type with the or operator.
While typing extra characters is not the end of the world, having a more concise representation of unions would be helpful. It also saves a few moments of thought when giving a value a type, then realizing it should actually be a union of types. Before, you would have to arrow-key both ways and surround them with "Union[" and "]" while with this new method you can simply append "or" and then the type. While not a world-changer, it might be useful.
A few clarifications for those interested:
This method of declaring unions will NOT replace "Union[...]". Instead, it will serve as syntactic sugar for representing the same thing.
The next is actually a question: do we use "bitwise or" or "boolean or" (aka "|" vs "or")? I honestly don't know which would be preferable. The latter is more readable than the other but requires 3-4 characters (including whitespace) vs just 1-3 extra. Both are shorter than the 8-9 chars for the traditional union. I'll just use both in the examples for now.
Finally, there are implementation details. There are some problems that should be addressed for both run-time and static analysis annotations.
For run-time, these new annotations would cause an error or unwanted result in current versions.
x: List | Tuple # TypeError: unsupported operand type(s) for |: ...
x: List or Tuple # evaluates to "List" because of truthiness
In either case, we could override the or-dunder method to return the "old" union representation of types
List | Tuple == Union[List, Tuple]
(Union[List, Tuple] or Union[int, str]) == Union[List, Tuple, int, str]
This should allow any code relying on run-time annotations to work as expected.
Note: I am uncertain if some versions of Python do not evaluate annotation expressions, but a quick test in 3.7 seems to show they do.
>>> var: print('This expression runs')
This expression runs
I don't have much to say about how this relates to static analysis. Long story short, if this becomes adopted, static analysis tools like Mypy will simply have to adapt. It will complicate the analysis process since there are now two ways to represent unions, but that's the way it would be.
Thoughts? Comments? Agreement of usefulness or blatant hatred for the suggestion? Let me know 😊