Technical
Python Typing Patterns I Use Daily
Python with type hints is a different language from Python without them. Not syntactically, but in how much the tooling can help you. Four months of consistent typing later, I can barely read untyped Python. Here are the patterns I rely on daily.
TypedDict for API Payloads
Every API endpoint accepts and returns JSON. TypedDict gives that JSON a type the editor understands. I use TypedDict at the boundary and convert to Pydantic models internally when I need validation.
from typing import TypedDict
class PostPayload(TypedDict):
title: str
body: str
published: bool
def handle_webhook(payload: PostPayload) -> None:
# editor knows payload['title'] is str
# typo like payload['titel'] is flagged
save_post(payload['title'], payload['body'])Protocol for Duck Typing
When I want to accept anything with a certain shape, Protocol is the answer. I stopped using abstract base classes for this. Protocol gives you duck typing with static checking, which is the best of both worlds.
Literal for Finite String Values
Status fields, event types, role names: all of these should be Literal types, not bare str. The editor autocompletes the allowed values and flags invalid ones. It is free correctness.
from typing import Literal
Status = Literal['draft', 'published', 'archived']
def set_status(post_id: str, status: Status) -> None:
# calling set_status(id, 'publshed') is flagged
...assert_never for Exhaustiveness
When I branch on a Literal or a union, typing.assert_never makes the compiler prove every case is handled. Add a new variant, forget to update the branches, the type checker catches it. This single pattern has caught real bugs in my code twice this quarter.
Running the Checker
Types without a checker are decoration. I run pyright on every file save via my editor, and mypy in CI. The two tools have slightly different strengths: pyright is faster and smarter about inference, mypy has better stubs for some libraries. Running both catches more issues than either alone.
See the Python typing module docs for the full surface area. The patterns above are the ones that earn their keep in day-to-day development.
RELATED READING
The Consulting Shift I Am Making In Year Two
After a year of writing and building, my consulting practice is changing shape. Shorter engagements. Sharper outcomes.
ReadThe Frontend Shift: Shipping Less JavaScript In Year Two
A year ago I reached for Next.js for everything. This year I often reach for nothing.
ReadThe Serverless Lesson I Would Write On A Sticky Note
After a year of shipping serverless projects, one rule explains most of the wins and all of the losses.
Read