Python Union in Typing – Specify Multiple Types

Python 3.5 introduced the concept of Typing Hinting as well as the typing library, where as we could specify a static type for variables and functions. Amongst the various features introduced in the Python Typing library, was the use of the Union function, which can be used to specify multiple possible types for a variable or function.

For a complete tutorial on Type Hinting in Python, refer to our dedicated tutorial, otherwise continue to our explanation of the Union function.


Combining together Types with Union

An interesting tool that the Python typing library gives us, is 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.

myVar: int

This variable will only accept integer values. As long as you have a static type checker running, an error will be thrown if you attempt to assign to it, anything that is not an integer.

Union on a Variable

Now let’s take a look at using Union on a variable. The syntax is very simple, and simply requires you to write the Union keyword, and within square brackets you include the types you wish to keep, separated by commas.

from typing import Union

# myVar accepts both integers and strings
myVar: Union[int, str] 

myVar = 5
myVar = "Hello"

The above commands are perfectly valid, as myVar accepts both integers and strings. Anything else of course, will produce an error.

Union on Lists and Dicts

Now let’s try using the Union on a container such as a List or Dictionary.

from typing import List, Dict, Tuple, Union

mylist: List[Union[int, str]] = ["a", 1, "b", 2]

The above command is perfectly valid, as both int and str are allowed in mylist.

For Tuples and Dictionaries as well, include Union[type1, type2] where ever they ask for a type. There is no limit to the number of types that you can include within Union.


This marks the end of the Union of Typing in Python Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments