Sling Academy
Home/Python/Python: Defining Functions with Type Hints

Python: Defining Functions with Type Hints

Last updated: March 04, 2023

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.

Next Article: Python Generic Types: Tutorial & Examples

Previous Article: Python: How to Retry After Exception – 3 Effective Ways

Series: Basic Python Tutorials

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types