Python · Chapter 39 of 45
Type Hints
TYPE HINTS annotate what types functions expect and return. They are optional and do NOT enforce anything at runtime — but tools like mypy, IDEs and Pyright use them to catch bugs.
Syntax: `def add(a: int, b: int) -> int:`.
Common types
int, str, float, bool, list[int], dict[str, int], tuple[int, str], Optional[X], Union[A, B] (or `A | B` in 3.10+).
Why bother?
Better autocomplete, catch mistakes earlier, self-documenting code.
Example 1 (python)
def greet(name: str, times: int = 1) -> str:
return ("Hi " + name + "! ") * times
print(greet("Ana", 3))Output
Hi Ana! Hi Ana! Hi Ana! Types are hints — Python still runs the code the same way.
Example 2 (python)
from typing import Optional
def find_user(id: int) -> Optional[str]:
users = {1: "Ana", 2: "Ben"}
return users.get(id)
print(find_user(3))Output
NoneOptional[str] means the return is either str or None.
Key points
- Optional — not enforced at runtime.
- Improve IDE autocomplete and static analysis.
- Use `Optional[X]` or `X | None`.
- Run `mypy` to check types.
💡 Note: Since Python 3.10, `int | None` works instead of `Optional[int]`.
