Writing

Python Type Hints: Foundations and Static Type Checking

Python is dynamically typed: variables are not bound to a fixed type, and their types can change during runtime. Dynamic typing allows rapid iteration and low syntactic overhead, but as codebases expand, passing unexpected types becomes a frequent source of runtime crashes.

Since Python 3.5 (and dramatically expanded through PEP 484, 585, and 604), Python includes standard support for type hints. Type annotations bring compile-time safety and IDE superpowers to Python without sacrificing interpreted flexibility.

The Core Advantages of Type Hinting

  1. Self-Documenting Code: Type signatures immediately clarify what functions expect and return without reading internal implementation details.
  2. Editor Intelligence: Modern IDEs and Language Servers (Pylance, Pyright) leverage annotations for precise autocompletion, instant parameter documentation, and inline refactoring.
  3. Early Error Detection: Tools like pyright or mypy catch type mismatches, missing attributes, and None-dereferences during CI or directly inside your editor.

[!NOTE] Python Version Note Since Python 3.9 (PEP 585), standard collection types like list[str], dict[str, int], and tuple[int, ...] can be parameterized directly without importing capitalized variants (List, Dict) from the typing module. Furthermore, Python 3.10 (PEP 604) introduced the pipe operator int | str as a cleaner replacement for Union[int, str].

Essential Types and Patterns

1. Primitives and Built-in Collections

Basic variables and functions use simple annotations:

name: str = "Alice"
age: int = 30
is_active: bool = True

def greeting(user: str, count: int = 1) -> list[str]:
    return [f"Hello {user}"] * count

2. Optional and Union Types (|)

When a variable can hold multiple types or can be None, use the union pipe operator:

# Modern Python (3.10+):
def fetch_token(header: str | None) -> str | None:
    if header is None:
        return None
    return header.removeprefix("Bearer ")

# Legacy equivalent (pre-3.10):
# from typing import Optional, Union
# def fetch_token(header: Optional[str]) -> Optional[str]: ...

3. Literal for Discrete Enumerations

Use Literal when a parameter must match specific constant strings or integers:

from typing import Literal

Mode = Literal["read", "write", "append"]

def open_file(path: str, mode: Mode = "read"):
    ...

4. TypedDict for Structured Dictionaries

When working with JSON or legacy dictionaries that have known schemas, TypedDict provides static key-type checking:

from typing import TypedDict

class UserProfile(TypedDict):
    id: int
    username: str
    email: str

def format_user(user: UserProfile) -> str:
    return f"{user['username']} <{user['email']}>"

[!TIP] If you are designing internal data objects from scratch rather than interacting with raw dictionaries, prefer @dataclass (or Pydantic models) over TypedDict.

5. Generators and Iterables (collections.abc)

Functions yielding items should be annotated using collections.abc.Iterator or Generator:

from collections.abc import Iterator

def countdown(start: int) -> Iterator[int]:
    while start > 0:
        yield start
        start -= 1

6. First-Class Functions (Callable)

When passing callbacks or higher-order functions, use Callable[[ParamTypes...], ReturnType]:

from collections.abc import Callable

def retry(operation: Callable[[str], bool], target: str) -> bool:
    for _ in range(3):
        if operation(target):
            return True
    return False

7. Classes as Arguments (type[T])

When a function accepts a class object itself rather than an instance:

class DatabaseError(Exception):
    pass

def expect_error(error_cls: type[Exception]):
    try:
        raise DatabaseError("Connection timed out")
    except error_cls as err:
        print(f"Caught expected error: {err}")

8. Escape Hatch: Any

Any disables type checking for a variable. While convenient when wrapping untyped legacy code, use it sparingly—relying on Any defeats the safety guarantees provided by static type checkers.


Continue to the next part in this series: Advanced Python Typing: TypeVar, Generic, and Protocol.