Type Hints in Python: A Practical Guide
Type hints don't change how Python runs, but editors and type checkers use them to catch bugs and power autocomplete. Modern Python syntax makes them short and readable.
The basics
def greet(name: str, times: int = 1) -> str:
return ", ".join([f"Hello {name}"] * times)
scores: dict[str, int] = {"asha": 90}
tags: list[str] = []
point: tuple[float, float] = (1.0, 2.5)
user_id: int | None = None # instead of Optional[int]
Structured dictionaries: TypedDict
from typing import TypedDict, NotRequired
class UserDict(TypedDict):
id: int
name: str
email: NotRequired[str]
def show(user: UserDict) -> None:
print(user["name"])
Duck typing with Protocol
from typing import Protocol
class SupportsClose(Protocol):
def close(self) -> None: ...
def shutdown(resources: list[SupportsClose]) -> None:
for r in resources:
r.close() # any object with close() is accepted, no inheritance needed
Generics (Python 3.12+ syntax)
def first[T](items: list[T]) -> T | None:
return items[0] if items else None
class Box[T]:
def __init__(self, value: T) -> None:
self.value = value
type UserId = int # type alias statement
Callables and literals
from collections.abc import Callable
from typing import Literal
Handler = Callable[[str], None]
def set_mode(mode: Literal["light", "dark"]) -> None: ...
Run a type checker
uv add --dev mypy
uv run mypy src/
Pyright (used by VS Code's Pylance) is another popular checker. Start without strict mode, type new code and public functions first, and tighten settings over time.
Was this article helpful?
Comments
No comments yet. Have a question or a tip? Be the first to share it.