Skip to content

Module 17 · Advanced Python Concepts — topic 11 of 14

Type hints

Annotating parameters and return values: basic and collection types, unions and optional values, TypedDict, how hints help editors and type checkers like mypy, and why Python doesn't enforce them at runtime.

Beginner 10 min read·Lesson 257 of 306 in Python Programming

Learning objectives

  • Add type hints to functions
  • Use collection, union and optional types
  • Run a type checker and understand its role

Definition

Type hints are optional annotations that state the expected types of variables, parameters and return values. Python stores them but does not check them; tools such as mypy, Pyright and editors use them to find mistakes before the code runs.

Introduction

def total(prices: list[float]) -> float tells readers, editors and type checkers exactly what the function expects and returns.

Why it matters

Type hints catch whole classes of bugs early, improve autocompletion, and serve as documentation that stays up to date.

Detailed explanation

Annotate parameters with name: type and return values with -> type.

Built-in generic types describe contents: list[str], dict[str, int], tuple[int, int], set[str].

Unions use |: int | str. A value that may be missing is written str | None (older code uses Optional[str]).

typing provides more tools: TypedDict for dictionaries with fixed keys, Callable for functions, Any as an escape hatch, Literal for specific values.

Python does not enforce hints: double("ab") still runs. A static checker (python -m mypy file.py) reports such mismatches without running the program.

typing.get_type_hints(func) returns the evaluated hints at runtime, which libraries such as dataclasses and pydantic use.

Add hints gradually, starting with public functions; they need not be perfect to be useful.

Syntax

Python
def average(values: list[float]) -> float | None:
return sum(values) / len(values) if values else None
  • name: type for parameters.
  • -> type for returns.
  • Checked by tools, not by Python.

Code examples

A hinted function

Python
def greet(name: str, times: int = 1) -> str:
return ", ".join([f"Hello {name}"] * times)
print(greet("Asha", 2))
print(greet.__annotations__)
Output
Hello Asha, Hello Asha
{'name': <class 'str'>, 'times': <class 'int'>, 'return': <class 'str'>}

Hints are not enforced

Python
def double(x: int) -> int:
return x * 2
print(double("ab"))
Output
abab

A type checker such as mypy would flag this call; Python itself runs it.

More examples

Collections, optional values and TypedDict

Python
import typing
from typing import TypedDict
def average(values: list[float]) -> float | None:
return sum(values) / len(values) if values else None
def index_by(items: list[dict[str, str]], key: str) -> dict[str, dict[str, str]]:
return {item[key]: item for item in items}
class Student(TypedDict):
name: str
marks: int
def top(students: list[Student]) -> Student:
return max(students, key=lambda s: s["marks"])
print(average([90.0, 80.5]), average([]))
people = [{"id": "u1", "name": "Asha"}, {"id": "u2", "name": "Ravi"}]
print(index_by(people, "id")["u2"]["name"])
print(top([{"name": "Asha", "marks": 91}, {"name": "Ravi", "marks": 78}])["name"])
print(typing.get_type_hints(average))
Output
85.25 None
Ravi
Asha
{'values': list[float], 'return': float | None}

Step-by-step explanation

  • float | None says average may return nothing for an empty list, so callers must handle None.
  • TypedDict documents the exact keys a student dictionary has; at runtime it is still an ordinary dict.
  • get_type_hints shows the evaluated hints that tools and libraries can inspect.

Expected output

Running “Collections, optional values and TypedDict” prints exactly:

TextOutput
85.25 None
Ravi
Asha
{'values': list[float], 'return': float | None}

Practical applications

  • Large code bases checked with mypy in CI.
  • FastAPI using hints to validate request data.

Best practices

  • Hint public functions first.
  • Use X | None for optional values.
  • Run a type checker regularly.

Common mistakes

Believing hints validate input

Avoid

def set_age(age: int):
self.age = age # strings still get through

Prefer

def set_age(age: int):
if not isinstance(age, int):
raise TypeError("age must be int")

Validate at runtime where it matters; hints alone don't.

Important notes

  • Python 3.14 evaluates annotations lazily, so forward references to classes defined later work without quotes.

Key takeaways

  • Hints describe expected types.
  • Python doesn't enforce them; checkers do.
  • Use generics, unions and TypedDict for precision.

Try it yourself

  1. 1
    Add full type hints to three functions from an earlier project and run mypy.
  2. 2
    Write a TypedDict for a product and a function that totals a list of them.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
Practise this topic