Type Hints

Annotate code with expected types for clarity and tooling.

Syntaxdef add(a: int, b: int) -> int:

Type hints let you document the types a function expects and returns. Python does not enforce them at runtime, but they make code clearer and let tools catch bugs before you run.

Reading a hint

def greet(name: str) -> str says name should be a string and the function returns a string.

Example

Example · python
def add(a: int, b: int) -> int:
    return a + b

def greet(name: str = 'Guest') -> str:
    return f'Hello, {name}'

print(add(3, 4))
print(greet('Ada'))

# Output:
# 7
# Hello, Ada

When to use it

  • An IDE uses type hints to autocomplete method names and flag incorrect argument types before running.
  • A mypy CI check catches a function returning None where a str is expected, preventing a runtime crash.
  • A library's public API uses type hints as documentation so callers know exactly what types to pass.

More examples

Function parameter and return hints

Annotates parameter types and the return type; hints are not enforced at runtime but aid tooling.

Example · python
def greet(name: str, times: int = 1) -> str:
    return (f'Hello, {name}! ' * times).strip()

print(greet('Alice'))      # Hello, Alice!
print(greet('Bob', 2))    # Hello, Bob! Hello, Bob!

Optional and Union types

Uses Optional[str] (equivalent to str | None) to declare a return type that may be absent.

Example · python
from typing import Optional

def find_user(user_id: int) -> Optional[str]:
    users = {1: 'Alice', 2: 'Bob'}
    return users.get(user_id)  # returns str or None

result = find_user(3)
if result is None:
    print('Not found')
else:
    print(result)

Variable annotations and list hints

Annotates a function that accepts and returns a list of ints, plus a variable annotation on the call site.

Example · python
from typing import List

def top_scores(scores: List[int], n: int) -> List[int]:
    return sorted(scores, reverse=True)[:n]

result: List[int] = top_scores([45, 90, 73, 88, 61], 3)
print(result)   # [90, 88, 73]

Discussion

  • Be the first to comment on this lesson.