The earlier Functions lesson used a basic type hint like -> int. This lesson covers the fuller typing system — Python never enforces these at runtime on its own, but they document intent and let a separate tool catch real mistakes before the code even runs.
def greet(name: str) -> str:
return f'Hello, {name}!'
age: int = 28
price: float = 19.99
is_active: bool = Truenames: list[str] = ['Sam', 'Alex']
scores: dict[str, int] = {'Sam': 90, 'Alex': 85}
coordinates: tuple[float, float] = (12.5, 45.2)from typing import Optional
def find_user(user_id: int) -> Optional[str]:
# Returns a username, or None if not found
...
# Python 3.10+ shorthand, no import needed:
def find_user(user_id: int) -> str | None:
...def process(value: int | str) -> str:
return str(value)from typing import Callable
def apply(func: Callable[[int], int], value: int) -> int:
return func(value)Python itself never checks these hints while running — mypy, run separately, catches a mismatch before the code even executes.
pip install mypy
mypy my_script.py
# my_script.py:5: error: Argument 1 to "greet" has incompatible type "int"; expected "str"| Hint | Means |
|---|---|
| list[str] | A list containing only strings |
| dict[str, int] | A dict with string keys and integer values |
| Optional[str] / str | None | A string, or None |
| int | str | Either an int or a string |
| Callable[[int], int] | A function taking an int and returning an int |
What Python itself actually does with these
Type hints are optional documentation, not enforcement — running the code with a "wrong" type still works fine unless something like mypy is run separately to check. Their value is catching a real class of bugs before runtime, and making a function's expected inputs obvious to anyone reading it.