advancedAdvanced Topics

Type Hints

Add type annotations for better code clarity and tooling support.

01Basic Type Hints

Annotate variables, parameters, and return types.

Python
1def greet(name: str) -> str:
2 return f"Hello, {name}!"
3
4def calculate(x: int, y: int) -> float:
5 return x / y
6
7age: int = 25
8name: str = "Alice"
9scores: list[int] = [95, 87, 92]
10
11print(greet(name))
12print(calculate(10, 3))
Output
Hello, Alice!
3.3333333333333335

02Complex Type Hints

Use typing module for advanced type annotations.

Python
1from typing import Optional, Union, TypeVar
2
3def find_user(user_id: int) -> Optional[dict]:
4 """Returns user dict or None."""
5 users = {1: {"name": "Alice"}, 2: {"name": "Bob"}}
6 return users.get(user_id)
7
8def process(value: Union[int, str]) -> str:
9 return str(value)
10
11print(find_user(1))
12print(find_user(99))
13print(process(42))
Output
{'name': 'Alice'}
None
42