Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do union types actually exist in python?

Since python is dynamically typed, of course we can do something like this:

def f(x):     return 2 if x else "s" 

But is this the way python was actually intended to be used? Or in other words, do union types exist in the sense they do in Racket for example? Or do we only use them like this:

def f(x):     if x:         return "s" 

where the only "union" we need is with None?

like image 895
Lana Avatar asked Aug 09 '16 15:08

Lana


People also ask

Does Python have union types?

Union type; Union[X, Y] is equivalent to X | Y and means either X or Y. To define a union, use e.g. Union[int, str] or the shorthand int | str . Using that shorthand is recommended.

What is a Python union?

Union() function in Python Union of two given sets is the set which contains all the elements of both the sets. The union of two given sets A and B is a set which consists of all the elements of A and all the elements of B such that no element is repeated. The symbol for denoting union of sets is 'U'

What is union in typing?

Combining together Types with Union This is a special keyword, which allows us to specify multiple allowed datatypes, instead of a single one. If for example, we wanted a string that allows both integers and strings, how would we do so? This is where Union helps. Let's take a look at a regular example first.


1 Answers

Union typing is only needed when you have a statically typed language, as you need to declare that an object can return one of multiple types (in your case an int or str, or in the other example str or NoneType).

Python deals in objects only, so there is never a need to even consider 'union types'. Python functions return what they return, if the programmer wants to return different types for different results then that's their choice. The choice is then an architecture choice, and makes no difference to the Python interpreter (so there is nothing to 'benchmark' here).

Python 3.5 does introduce a standard for creating optional type hints, and that standard includes Union[...] and Optional[...] annotations. Type hinting adds optional static type checking outside of the runtime, the same way types in TypeScript are not part of the JavaScript runtime.

like image 121
Martijn Pieters Avatar answered Sep 23 '22 23:09

Martijn Pieters