This concise, example-based article shows you how to define functions with type hints in Python.
Overview
Python 3.5 introduced Type Hints which allows you to specify the data type of a function’s parameters and return value. It can be very helpful in preventing bugs (especially useful when you are looking back at your code after a long time of inactivity or when you work in a team) and making the code more understandable.
To define functions with type hints, you can use the -> syntax to indicate the expected return type after the function parameters. You can also specify the data types for the parameters using the : syntax.
def function_name(parameter1: type, parameter2: type, ...) -> return_type:
# Function body
return value
For more clarity, see the examples below (they are arranged in order from basic to advanced).
Example: Primitive Data Types
Suppose you want to create a function named add that takes two integers and returns their sum. Here’s how you can define it with type hints:
def add(num1: int, num2: int) -> int:
return num1 + num2
Try it:
result = add(2, 3)
print(result) # Output: 5
Example: Dictionary Parameter
Let’s say you want to create a function named calculate_total_cost that takes a dictionary of items and their prices and returns the total cost of all the items. Here’s how you can define it with type hints:
def calculate_total_cost(items: dict[str, float]) -> float:
total_cost = sum(items.values())
return total_cost
Call the function and see its output:
items = {'apple': 0.5, 'banana': 0.25, 'orange': 0.75}
total_cost = calculate_total_cost(items)
print(total_cost) # Output: 1.5
Example: List Parameter
In this example, we’ll create a function named calculate_grade that takes a list of scores and returns the grade based on the average score:
def calculate_grade(scores: list[float]) -> str:
avg_score = sum(scores) / len(scores)
if avg_score >= 90:
return 'A'
elif avg_score >= 80:
return 'B'
elif avg_score >= 70:
return 'C'
elif avg_score >= 60:
return 'D'
else:
return 'F'
scores = [85, 90, 75, 80]
grade = calculate_grade(scores)
print(grade) # Output: B
Example: Function that Returns Multiple Values
In this example, we’ll define a function with type hints named get_statistics that takes a list of numbers and returns multiple values – the minimum, maximum, and average of the numbers.
def get_statistics(numbers: list[float]) -> tuple[float, float, float]:
minimum = min(numbers)
maximum = max(numbers)
average = sum(numbers) / len(numbers)
return minimum, maximum, average
numbers = [2.5, 4.8, 1.7, 3.2, 5.1]
minimum, maximum, average = get_statistics(numbers)
print(f"Minimum: {minimum}, Maximum: {maximum}, Average: {average}")
# Output: Minimum: 1.7, Maximum: 5.1, Average: 3.06
Afterword
You’ve learned how to define a function with type hints in Python and walked through a couple of examples of applying that knowledge in practice. From this point, you can make more complex and complicated programs with more confidence. Defining a function with type hints isn’t mandatory, but it’s very useful and would help you avoid a great deal of trouble in the future.