1.Basic annotations
A type annotation writes the expected type after a colon — name: type for a variable, param: type for an argument, -> type for a return value. Python stores it but never checks it while running.
Key features
- name: type annotates a variable; param: type annotates a function argument
- -> type after the parameter list annotates the return value
- Annotations are optional and have zero effect on how the code actually runs
- A type checker (mypy, pyright) reads annotations; the interpreter does not enforce them
- Available on variables, function parameters, and return values since Python 3.5 (PEP 484)
- x: int — variable annotation
- def f(x: int) — parameter annotation
- -> str: — return annotation
Command
age: int = 5
def greet(name: str, times: int = 1) -> str:
return (name + " ") * timesname: type / param: type / -> type documents the expected type. Python stores it and never checks it while running.