How to Specify Multiple Possible Types for a Variable in Python?

Estimated read time 2 min read

In Python, you can specify multiple possible types for a variable by using the Union type from the typing module. The Union type allows you to specify a list of two or more types that a variable can have.

Here’s an example:

from typing import Union

def get_length(x: Union[str, list, tuple]) -> int:
    return len(x)

In this example, we define a function called get_length that takes a variable x as input, which can be either a string, a list, or a tuple. The function returns the length of x as an integer.

The Union type allows us to specify multiple possible types for x in the function signature. In this case, we specify that x can be either a str, a list, or a tuple.

Note that when using the Union type, you should list the types in order of decreasing specificity. In other words, more specific types should appear before more general types. For example, if you have a function that can accept either an integer or a float, you should list the int type first and the float type second:

from typing import Union

def square(x: Union[int, float]) -> Union[int, float]:
    return x ** 2

In this example, we define a function called square that takes a variable x as input, which can be either an integer or a float. The function returns the square of x, which can also be either an integer or a float.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply