Type Hints
Annotate function signatures and variables for better tooling and documentation
Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.
UpgradeKnowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
Python is dynamically typed, but :type-hint[An annotation that specifies expected types without runtime enforcement, checked by tools like mypy]s (PEP 484) let you annotate types for tools and readability. They are checked by tools like mypy and IDEs — not enforced at runtime.
Function annotations:
python def greet(name: str, times: int = 1) -> str: return name * times def process(items: list[int]) -> dict[str, int]: return {'count': len(items), 'sum': sum(items)}
Variable annotations:
python age: int = 25 name: str = 'Alice' scores: list[float] = [9.5, 8.2, 9.8]
Common types from `typing` module (Python < 3.9):
python from typing import Optional, Union, List, Dict, Tuple def find(name: str) -> Optional[str]: # str or None ... def parse(val: Union[int, str]) -> str: # int OR str ...
Python 3.10+ syntax (cleaner):
python def find(name: str) -> str | None: # | instead of Union ...
Why type hints matter: Catch bugs before runtime, better IDE autocomplete, self-documenting code. Essential in production Python.
Examples
Type-annotated function
Optional[X] means the value can be X or None
from typing import Optional
def get_user_age(user_id: int, default: Optional[int] = None) -> Optional[int]:
"""Return user age, or default if not found."""
users = {1: 25, 2: 30}
return users.get(user_id, default)
age: Optional[int] = get_user_age(1) # 25
missing: Optional[int] = get_user_age(99) # NoneHow well did you understand this?
Next in Python Core
Lists — Advanced Patterns