Type Hints#

Static type annotation syntax supported natively since Python 3.9+ without importing List, Dict, or Optional from typing. Note that Python does not enforce type hints at runtime unless checked with external tools like mypy or pyright.

Basic Syntax#

  • Built-in Generics: list[int], dict[str, int], set[str]
  • Tuples:
    • Fixed-length: tuple[int, str]
    • Variable-length homogeneous: tuple[int, ...]
  • Union and Nullable (Python 3.10+): int | str, list[int] | None
  • Callables: Callable[[Arg1Type, Arg2Type], ReturnType] from collections.abc

eg.

from collections.abc import Callable


def apply(nums: list[int], fn: Callable[[int], int]) -> list[int]:
    return [fn(x) for x in nums]

Classes and Self-Referential Types#

A class can hold attributes referencing its own type such as list[Node] for two reasons:

  • Object Reference Semantics: Variables and list elements store PyObject* pointers rather than embedded by-value objects, working like std::vector<Node*> in C++. See Passing Mechanism.
  • Deferred Annotation Evaluation: While executing a class Node: block, the name Node is not bound yet, which normally raises NameError. Declaring from __future__ import annotations postpones annotation evaluation (like a C++ forward declaration) so Node can be referenced directly inside its own class definition.

Avoiding Mutable Default Arguments in __init__#

Default argument objects are evaluated once at function definition time. Never use [] or {} directly as a default parameter; accept None and allocate a new container inside __init__.

eg.

from __future__ import annotations


class Node:
    def __init__(self, val: int, children: list[Node] | None = None) -> None:
        self.val: int = val
        self.children: list[Node] = list(children) if children else []