← Python lessons

Python Type Hints: Annotating Variables and Functions

Python type hints describe the types you expect for variables, parameters and return values. Editors and type checkers use them to find mistakes.

Annotate a variable

Write a colon and a type after the variable name.

score: int = 8
name: str = "Ada"
ready: bool = True
print(name, score, ready)

This prints Ada 8 True. The annotations describe the values without changing them.

Annotate parameters and return values

Put -> and the return type after the closing parenthesis.

def add_bonus(score: int, bonus: int) -> int:
    return score + bonus

print(add_bonus(8, 2))

This prints 10. Use -> None for a function that returns no useful value.

Annotate lists and dictionaries

Use square brackets for the types stored inside a collection.

scores: list[int] = [8, 6]
players: dict[str, int] = {"Ada": 8, "Sam": 6}
print(sum(scores))
print(players["Ada"])

This prints 14, then 8. dict[str, int] means string keys and integer values.

Understand what hints check

Python does not enforce type hints while running code. They do not convert values.

score: int = "eight"  # a type checker reports this mismatch
print(score)

Python still prints eight. A separate type checker, such as mypy or Pyright, reports mismatches.

Note: list[int] and dict[str, int] require Python 3.9 or later.

See also: Parameters and return, Optional and union types, Protocol.

Your turn

Add a function named double with an int parameter and an int return hint. Return twice its argument.

# add two lines: define double(number: int) -> int, then return twice number
print(double(6))

Expected output

12

Practise this in the free Python course, where every exercise checks your code instantly.