In Python, type hints are used to provide information about the types of variables, function arguments, and return values. When you want to hint that a function or a variable should be a tuple, you can use the Tuple
type hint from the typing
module. The Tuple
type hint takes the individual types of elements in the tuple as its arguments.
Here’s the syntax for using the Tuple
type hint:
from typing import Tuple
# Function with a Tuple type hint for the return value
def example_function() -> Tuple[int, str]:
return (42, "Hello")
# Function with a Tuple type hint for the arguments
def process_tuple(data: Tuple[int, str]):
num, text = data
print(f"Number: {num}, Text: {text}")
Keep in mind that type hints are just hints; Python is still a dynamically typed language, and type hints do not enforce types at runtime. They are used mainly for documentation purposes and can be used by type-checking tools to catch type-related errors before runtime.
Python type hints tuple example
Here’s an example that demonstrates the use of type hints with tuples in Python:
from typing import Tuple
# Function with a Tuple type hint for the return value
def create_person() -> Tuple[str, int, str]:
name = "Alice"
age = 30
occupation = "Engineer"
return name, age, occupation
# Function with a Tuple type hint for the arguments
def print_person(person_data: Tuple[str, int, str]):
name, age, occupation = person_data
print(f"Name: {name}, Age: {age}, Occupation: {occupation}")
# Example usage
person_info = create_person()
print_person(person_info)
Output:
In this example, we have two functions. The first function create_person
returns a tuple containing three elements: a string (name), an integer (age), and another string (occupation). We specified this tuple type using the Tuple[str, int, str]
type hint.
The second function print_person
takes a tuple as an argument, and again, we used the Tuple[str, int, str]
type hint to specify the type of the argument.
In the example usage part, we call the create_person
function to obtain a tuple containing the information of a person. Then, we pass that tuple to the print_person
function to display the person’s details.
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.