Add Type Hints to Function Parameters and Return in Python

Add type hints to function parameters and return values in Python for clearer, more maintainable code using the typing module.

Easy Python 3.8+ Aug 9, 2026 Functions & basics 15 views 0 copies

Python code

23 lines
Python 3.8+
from typing import List, Optional, Dict


def average(numbers: List[float]) -> float:
    return sum(numbers) / len(numbers)


def full_name(first: str, last: Optional[str] = "") -> str:
    return f"{first} {last}".strip()


def build_user(name: str, age: int, email: Optional[str] = None) -> Dict[str, object]:
    user = {"name": name, "age": age}
    if email:
        user["email"] = email
    return user


if __name__ == "__main__":
    nums = [10.5, 20.0, 30.25]
    print(f"Average: {average(nums)}")
    print(f"Full name: {full_name('Jane', 'Doe')}")
    print(f"User: {build_user('Bob', 30, 'bob@example.com')}")

Output

stdout
Average: 20.25
Full name: Jane Doe
User: {'name': 'Bob', 'age': 30, 'email': 'bob@example.com'}

How it works

Type hints allow you to document the expected types of function parameters and return values directly in the code. The typing module provides generic types like List, Dict, and Optional for more precise annotations. Using Optional[str] indicates the parameter can be a string or None. Type hints are not enforced at runtime, but tools like mypy and IDEs use them for static checking and autocomplete.

Common mistakes

  • Using `List` and `Dict` without importing from `typing` in older Python versions
  • Forgetting that `Optional[str]` is shorthand for `Union[str, None]`
  • Assuming type hints enforce type checking at runtime
  • Using lowercase `list` and `dict` in Python versions before 3.9

Variations

  1. Use built-in generics like `list[float]` and `dict[str, object]` with Python 3.9+
  2. Use `from __future__ import annotations` to defer evaluation of annotations

Real-world use cases

  • Documenting function contracts in a shared library or SDK for other developers.
  • Enabling static type checking in CI pipelines to catch type mismatches before deployment.
  • Improving IDE autocomplete and refactoring safety for large codebases.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.