Python Type Hints Guide

Master Python type hints for better code documentation, IDE support and static analysis

Python Type Hints Guide

Type hints make your Python code more readable, maintainable, and catch bugs before runtime.

Basic Syntax

def greet(name: str) -> str:
    return f"Hello, {name}!"

def add(a: int, b: int) -> int:
    return a + b

Common Types

from typing import Optional, Union, Any

# Optional - can be None
def find_user(user_id: int) -> Optional[User]:
    ...

# Union - multiple types (Python 3.10+: use |)
def process(value: Union[str, int]) -> str:
    ...

# Python 3.10+ syntax
def process(value: str | int) -> str:
    ...

Collections

# Lists
names: list[str] = ["Alice", "Bob"]

# Dictionaries
ages: dict[str, int] = {"Alice": 30, "Bob": 25}

# Sets
unique_ids: set[int] = {1, 2, 3}

# Tuples (fixed length)
point: tuple[int, int] = (10, 20)

Type Aliases

from typing import TypeAlias

UserId: TypeAlias = int
UserMap: TypeAlias = dict[UserId, "User"]

def get_users() -> UserMap:
    ...

Static Type Checking

Use mypy or pyright to verify types:

mypy your_module.py
pyright your_module.py

Both integrate with most IDEs for real-time feedback.