In Python, the Union type is used to represent a type that can be one of multiple data types. It allows you to specify that a variable or function parameter can accept values of different types. The Union type is particularly useful in situations where a value can be of more than one specific type, and you want to ensure that the variable or parameter can accommodate any of those types.
The Union type is part of the typing
module, introduced in Python 3.5 and later versions. To use the Union type, you need to import it from the typing
module. Here’s the general syntax:
from typing import Union
variable: Union[type1, type2, ...]
In this syntax, type1
, type2
, etc., represent the different data types that the variable can accept.
Python Union type example
Here’s an example of using Union type:
from typing import Union
def display_value(input_value: Union[int, float, str]) -> None:
print(f"The value is: {input_value}")
display_value(42)
display_value(3.14)
display_value("Hello")
Output:
In the above example, the display_value
function can accept integers, floats, or strings as its input, thanks to the Union type.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.