Sub topic 3
Python Type Hints: Advanced Type Shapes
Assume you know Python functions, classes, built-in collections, and how to run scripts and install packages with pip. These hints help a static checker such as mypy or pyright find mistakes before execution.
Restricting values with Literal and Final
Literal limits a value to specific choices. Final marks a name that should not be reassigned.
from typing import Final, Literal
MAX_RETRIES: Final = 3
Mode = Literal["r", "w"]
def open_log(path: str, mode: Mode) -> None:
print(f"opening {path} in {mode} mode")
open_log("app.log", "r")A checker rejects open_log("app.log", "x") and assignments such as MAX_RETRIES = 4.
Annotating classes and dataclasses
Annotate instance attributes in __init__, or use a dataclass to generate initialization code.
from dataclasses import dataclass
@dataclass
class User:
name: str
active: bool = TrueGeneric functions with TypeVar
A TypeVar links input and output types. This function returns an element of the same type as its sequence.
from collections.abc import Sequence
from typing import TypeVar
T = TypeVar("T")
def first(items: Sequence[T]) -> T:
return items[0]Structural typing with Protocol
A Protocol describes required behavior. An object matches it by having the required methods, without inheriting from the protocol.
from typing import Protocol
class Closable(Protocol):
def close(self) -> None: ...
def shutdown(resource: Closable) -> None:
resource.close()Dictionary shapes with TypedDict
TypedDict describes required keys and their value types.
from typing import TypedDict
class Movie(TypedDict):
title: str
year: intForward references and postponed evaluation
A forward reference names a class before it is defined. Postponed evaluation keeps annotations from being evaluated immediately.
from __future__ import annotations
class Node:
def __init__(self, child: Node | None = None):
self.child = childGeneric classes
A generic class carries a type parameter.
from typing import Generic, TypeVar
T = TypeVar("T")
class Box(Generic[T]):
def __init__(self, value: T):
self.value = value
number_box: Box[int] = Box(10)Varying signatures with overload
@overload documents several accepted signatures. The final implementation handles them at runtime.
from typing import overload
@overload
def repeat(value: str, count: int) -> str: ...
@overload
def repeat(value: list[str], count: int) -> list[str]: ...
def repeat(value: str | list[str], count: int) -> str | list[str]:
return value * countAdding hints to an existing codebase
Add annotations at public function boundaries first. Run a checker, fix clear errors, and then expand inward. Use Any temporarily when information is unavailable, object when all values are accepted but operations must be checked, and a precise type whenever possible.
Exercise
What type should describe a function that accepts only the strings "json" or "csv"?
Show answer
Use Literal["json", "csv"].