Basic Type Annotations
Annotate function parameters and return types with : type and -> type.
Python
# Before type hints (ambiguous)
def add(a, b):
return a + b
# With type hints (self-documenting)
def add(a: int, b: int) -> int:
return a + b
def greet(name: str, times: int = 1) -> str:
return (f"Hello, {name}! " * times).strip()
# Variable annotations
age: int = 25
name: str = "Alice"
prices: list[float] = [1.99, 2.49, 0.99]Tip
Type hints are optional and not enforced at runtime. Use them for documentation and tooling benefits.
The typing Module
For complex types use Optional, Union, Callable, Tuple.
Python
from typing import Optional, Union, Callable, Tuple
# Optional: value can be None
def find_user(user_id: int) -> Optional[str]:
users = {1: "Alice", 2: "Bob"}
return users.get(user_id) # Returns str or None
# Union: one of several types
def process(value: Union[int, float, str]) -> str:
return str(value)
# Callable: function type
def apply(func: Callable[[int], int], n: int) -> int:
return func(n)
# Tuple with specific types
Point = Tuple[float, float]
def distance(p: Point) -> float:
return (p[0]**2 + p[1]**2) ** 0.5βΆ Output
None
"42"
25.0Modern Type Hints (Python 3.10+)
Python 3.10+ allows cleaner syntax for Union and Optional.
Python
# Python 3.10+ β use | instead of Union
def process(value: int | float | str) -> str:
return str(value)
# Optional is just X | None
def find(id: int) -> str | None:
return None
# Built-in generics (no need to import from typing)
def average(numbers: list[float]) -> float:
return sum(numbers) / len(numbers)
def get_config() -> dict[str, str]:
return {"host": "localhost"}Ad β 336Γ280
Type Hints with dataclasses
Type hints are required in dataclasses to define fields.
Python
from dataclasses import dataclass
from typing import ClassVar
@dataclass
class Product:
name: str
price: float
quantity: int = 0
tax_rate: ClassVar[float] = 0.08 # Class variable
def total_price(self) -> float:
return self.price * (1 + self.tax_rate)
p = Product("Coffee", 3.50, 10)
print(p.name, p.total_price())βΆ Output
Coffee 3.78