Type Hints & Annotations
Type hints make Python code more readable and catch bugs early. They're optional but recommended for professional code. Use mypy for static type checking.
15 min•By Priygop Team•Updated 2026
Type Hints
Type Hints
from typing import List, Dict, Optional, Union, Tuple, Callable
# Basic type hints
def greet(name: str) -> str:
return f"Hello, {name}!"
def add(a: int, b: int) -> int:
return a + b
# Collection types
def average(numbers: List[float]) -> float:
return sum(numbers) / len(numbers)
# Optional (can be None)
def find_user(user_id: int) -> Optional[Dict[str, str]]:
users = {1: {"name": "Alice"}, 2: {"name": "Bob"}}
return users.get(user_id)
# Union types
def process(data: Union[str, int]) -> str:
return str(data)
# Python 3.10+ syntax (cleaner!)
def process_new(data: str | int) -> str:
return str(data)
# Callable type
def apply(func: Callable[[int, int], int], a: int, b: int) -> int:
return func(a, b)
# Class with type hints
class User:
def __init__(self, name: str, age: int, email: Optional[str] = None):
self.name = name
self.age = age
self.email = email
def to_dict(self) -> Dict[str, Union[str, int]]:
return {"name": self.name, "age": self.age}
# Demo
print(greet("Alice"))
print(add(5, 3))
print(average([1.0, 2.0, 3.0]))
print(find_user(1))
print(apply(add, 5, 3))
user = User("Alice", 25, "alice@email.com")
print(user.to_dict())Tip
Tip
Use @dataclass(frozen=True) for immutable data. Use field(default_factory=list) for mutable defaults. Dataclasses replace boilerplate __init__.
Diagram
Loading diagram…
@dataclass auto-generates __init__, __repr__, __eq__
Common Mistake
Warning
Using mutable defaults in dataclass fields. Use field(default_factory=list) instead of field(default=[]). Same as regular function defaults.
Quick Quiz
Practice Task
Note
(1) Create a User dataclass with validation in __post_init__. (2) Make it frozen (immutable). (3) Add comparison with order=True.