Python Tutorial · Going Further · Lesson 39 of 42

Python Type Hints

Annotate functions and variables so editors and type checkers catch bugs early.

Annotations

Type hints document what a function expects and returns. Python doesn't enforce them at runtime — tools like mypy and pyright (and your editor) check them.

Example 1Try it yourself
def total_price(prices: list[float], tax_rate: float = 0.2) -> float:
    return round(sum(prices) * (1 + tax_rate), 2)

print(total_price([10.0, 5.5]))
print(total_price.__annotations__)

Output

18.6
{'prices': list[float], 'tax_rate': <class 'float'>, 'return': <class 'float'>}

Common types

  • Built-ins: int, str, list[int], dict[str, float], tuple[int, int]
  • Optional values: str | None (Python 3.10+)
  • Functions: Callable[[int], str] from collections.abc
Example 2Try it yourself
from collections.abc import Callable

def find_user(users: dict[int, str], user_id: int) -> str | None:
    return users.get(user_id)

def apply(fn: Callable[[int], int], value: int) -> int:
    return fn(value)

print(find_user({1: "Ada"}, 2))
print(apply(lambda x: x * 10, 4))

Output

None
40

Type hints pay off most in larger codebases and APIs — frameworks like FastAPI and Pydantic even use them to validate data.

Test yourself

Does Python raise an error at runtime if you pass a str to a parameter annotated as int?

  1. Yes
  2. No
Show answer

Answer: No

Type hints are not enforced at runtime; type checkers and editors use them.