
Python 3.5+ supports optional type annotations. They don't enforce types at runtime but help IDEs, linters, and other developers.
Basic annotations:
def greet(name: str) -> str:
return f"Hello, {name}"
def add(a: int, b: int) -> int:
return a + b
def get_scores() -> list[int]:
return [95, 87, 92]Variables:
name: str = "Alice"
age: int = 30
scores: list[int] = [95, 87]
config: dict[str, str] = {}Optional & Union:
from typing import Optional, Union
def find_user(id: int) -> Optional[str]:
# returns str or None
pass
def process(value: Union[int, str]) -> str:
return str(value)Type checking: Run mypy yourfile.py to catch type errors before runtime. Install: pip install mypy.
Why bother: Catches bugs early, improves autocomplete, makes code self-documenting.
Reference:
TaskLoco™ — The Sticky Note GOAT