advancedAdvanced Topics
Type Hints
Add type annotations for better code clarity and tooling support.
In this lesson
01Basic Type Hints
Annotate variables, parameters, and return types.
Python
1def greet(name: str) -> str:2 return f"Hello, {name}!"34def calculate(x: int, y: int) -> float:5 return x / y67age: int = 258name: str = "Alice"9scores: list[int] = [95, 87, 92]1011print(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, TypeVar23def 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)78def process(value: Union[int, str]) -> str:9 return str(value)1011print(find_user(1))12print(find_user(99))13print(process(42))
Output
{'name': 'Alice'}
None
42