All chapters in this track
- 011. Variables, Types & Operators
- 022. Strings
- 033. Lists
- 044. Tuples, Sets & Dicts
- 055. Control Flow
- 066. Error Handling
- 077. Functions & Lambdas
- 088. Comprehensions
- 099. Built-in Functions
- 1010. Type Hints (3.10+)
- 1111. Classes & Dataclasses
- 1212. Iterators & Generators
- 1313. DSA Standard Library
- 1414. Python 3.9–3.11 Features for DSA
- 1515. DSA Idioms & Gotchas
- 1616. Master Quick Reference
Chapter 10 of 16
10. Type Hints (3.10+)
Tutorial
Python 3.10+ introduced X | Y union syntax, replacing Optional[X] and Union[X, Y]. Python 3.9+ allows built-in collection types directly in hints.
# ── Modern type hints (3.9+) ───────────────────────────────────
# No longer need to import from typing for basic types
def process(arr: list[int]) -> dict[str, int]: ... # 3.9+
def pair(a: tuple[int, int]) -> set[str]: ... # 3.9+
# ── Union type (3.10+) ─────────────────────────────────────────
# Old (still works): from typing import Optional; Optional[int]
# New (3.10+):
def search(arr: list[int], target: int) -> int | None:
...
def parse(val: str | int | float) -> float:
return float(val)
# ── Class self-reference ──────────────────────────────────────
class ListNode:
def __init__(self, val: int = 0, next: "ListNode | None" = None):
self.val = val
self.next = next
# Python 3.11+: typing.Self (more precise than string annotation)
from typing import Self
class TreeNode:
def __init__(self, val: int = 0,
left: Self | None = None,
right: Self | None = None):
self.val = val
self.left = left
self.right = right
# ── TypeAlias (3.10+) ─────────────────────────────────────────
from typing import TypeAlias
Graph: TypeAlias = dict[int, list[int]]
Matrix: TypeAlias = list[list[int]]
# ── Common DSA type hint patterns ─────────────────────────────
def bfs(graph: dict[int, list[int]], start: int) -> list[int]: ...
def dijkstra(graph: dict[int, list[tuple[int,int]]], src: int) -> list[int]: ...
def knapsack(wt: list[int], val: list[int], W: int) -> int: ...
Reference
| Old syntax | Modern (3.9+/3.10+) | Version |
|---|---|---|
List[int] | list[int] | 3.9+ |
Dict[str,int] | dict[str,int] | 3.9+ |
Tuple[int,int] | tuple[int,int] | 3.9+ |
Set[str] | set[str] | 3.9+ |
Optional[int] | int | None | 3.10+ |
Union[int,str] | int | str | 3.10+ |
"ListNode" forward ref | Self | 3.11+ |
TypeAlias | from typing import TypeAlias | 3.10+ |