Skip to navigation

Python TypedDict Boundaries: Stop Model Drift With Claude Code

In short: Find dictionary-shaped API boundaries that need precise keys, then separate required fields from optional ones.

Published 20 min read
On this page

Direct answer

A dict[str, Any] at an API boundary is where model drift hides, because the annotation promises nothing about which keys exist or whether they are required. TypedDict fixes the shape: it models object-shaped dictionaries, and PEP 655 adds Required and NotRequired markers for individual keys. The migration is a boundary inventory, not a codebase-wide conversion. Pick the boundaries where two teams or two systems meet, decide for each key whether it is truly optional or merely missing, and record the decision. The concrete win is a boundary where the checker tells a producer it forgot a key. The concrete loss is that TypedDict performs no runtime validation, so a value the application never supplied will still flow through at execution time.

Ask Claude Code to inventory the dict[str, Any] sites and the producers and consumers around each one. The agent can find the boundaries. Deciding which keys are required is a contract decision that needs the data’s actual shape, and that is the reviewer’s job.

Why drift at a boundary is expensive

A boundary is a place where two owners meet: a client and a server, a service and a queue, a parser and a domain model. When the contract is dict[str, Any], neither side can see a change. A producer drops a key, a consumer reads a key that is no longer there, and the failure surfaces far from the edit that caused it.

The cost is not the missing key. The cost is the distance between the edit and the symptom. A key removed in a producer module breaks a consumer three modules away, and the traceback points at the consumer. Adding a precise boundary type turns that into a static error at the producer, where the edit happened.

There is a second cost: invented data. A team that migrates to TypedDict by writing down every key a consumer wishes existed has documented a fiction. The annotation then describes a contract nobody implements, which is worse than the loose dictionary because it is trusted.

Evidence and its limits

Official, F005: PEP 655 adds Required and NotRequired markers for individual TypedDict keys, and TypedDict models object-shaped dictionaries. The standard library page for typing.TypedDict and the mypy TypedDict page document checker behavior. These pages were not full-page fetched in the research pass, so recheck the exact wording before citing them further. Language and checker support varies.

Official, agent loop: Claude Code best practices recommends a check that returns pass or fail. In a boundary migration the check is the static checker plus the existing tests, run before and after the type is introduced.

Derived, F006: A boundary inventory that separates truly optional keys from missing data is an editorial migration method. Nothing here says typing changes runtime validation, and nothing requires every dictionary to become a TypedDict.

Nothing here claims an annotation proves runtime behavior, and the post includes no benchmark or adoption figure.

What TypedDict does and does not do

TypedDict describes a dictionary shape at the type level. A static checker learns from it which keys a dictionary should have and, with PEP 655, which are required. Runtime validation is absent, missing values are not created, and extra keys are not rejected at execution time.

This limitation is the whole point of the review discipline in this post. A TypedDict annotation is a shared agreement about shape. The agreement is only as good as the evidence behind each key.

Question TypedDict answer
Which keys should exist Yes, declared per type
Which keys are required Yes, with Required / NotRequired
Runtime validation No
Creates missing values No
Rejects extra keys at runtime No

Read the table before writing the type. A boundary where the data is untrusted, such as an external API response parsed at runtime, needs a validator alongside the TypedDict, not instead of it.

Required vs optional keys

PEP 655 lets a single key be marked Required or NotRequired inside a type where the default totalness would say otherwise. The decision for each key is factual, not stylistic: does the data actually contain this key in every valid instance?

Truly optional keys are ones the application handles in their absence. A response field that only appears for certain resource types is optional. A field the producer added in a later version and older producers omit is optional for consumers that must accept both.

Missing data is different. A key that should be present but is absent because of a bug is not optional. Marking it NotRequired to silence the checker converts a defect into a documented contract, the specific failure this post warns against.

Key Present in every valid instance Marker Reason
id Yes required Every record has an id
email Yes required Producer always sends it
middle_name No NotRequired Optional user field
legacy_ref No NotRequired Older producers omit it
status_detail No NotRequired only if handled Must confirm consumer handles absence

The last row is where review earns its keep. Mark a key optional only when the consumer demonstrably handles its absence.

Find dictionary-shaped contracts

Start from the loose annotations, then narrow to the boundaries that matter. A dict[str, Any] deep inside one function is a local detail. A dict[str, Any] crossing a module or service line is a boundary.

bash
# find loose dictionary annotations
rg -n "dict\[str, Any\]" src/
rg -n "dict\[" src/ | rg -v "dict\[str, (int|float|str)\]"

Each hit gets three facts recorded: the producer that builds the dictionary, the consumer that reads it, and whether the pair crosses an ownership line. The hits that cross a line are the migration candidates. Everything else can stay a plain dictionary until it becomes a boundary.

A package with a handful of internal helpers may have no true boundaries. A package with a client, a webhook parser, and a message consumer usually has several. The point of the inventory is to find where precision pays, not to convert every dictionary.

Claude Code can produce this inventory from the repository, and the draft needs review. The agent sees annotations and call sites but does not know which pairs cross an ownership line. Review each candidate against the question the inventory asks.

Map producers and consumers

A boundary type needs both sides visible. A TypedDict introduced without knowing the producer documents a guess.

Boundary Producer Consumer Crosses ownership Type candidate
Webhook payload External provider Parser module Yes PaymentWebhook
Queue message Producer service Consumer service Yes OrderEvent
Internal cache entry Repository layer Same layer No leave as dict
CLI config User file Loader Yes CliConfig

The internal cache row is the discipline: not every dictionary is a boundary, and converting it adds surface without benefit. The Claude Code overengineering guide covers how a small request can become a large diff; converting every dictionary is that failure applied to typing.

List, per candidate boundary, the keys the producer actually supplies. Read the producer code or a captured payload. Do not list keys a consumer wishes were there.

Introduce one boundary type

Add the type at the boundary, not at every use of the dictionary. A TypedDict is most useful where it is the declared parameter or return type of the function that crosses the line.

bash
from typing import TypedDict, NotRequired

class OrderEvent(TypedDict):
  order_id: str
  amount_cents: int
  currency: str
  coupon_code: NotRequired[str]

Run the static checker after introducing the type. Expect errors at producers that omit a required key and at consumers that read a key the producer does not supply. Those errors are the value of the change. Fix them by correcting the data or the code, not by weakening the type.

Introduce one boundary type per change. A migration that converts five boundaries at once produces a diff nobody can review against the actual data. Splitting the migration so each boundary is independently verifiable and revertible is the same discipline the Claude Code legacy code guide applies to unfamiliar code: shrink the unit until the evidence is unambiguous.

Review missing and extra keys

Two reviews decide whether the boundary is honest. The first is a missing-key review: for every required key, find the producer code that supplies it. The second is an extra-key review: for every key a consumer reads, confirm the producer supplies it.

A key that no producer supplies is the defect to catch. It is tempting to add it to the TypedDict because a consumer reads it and the checker is quiet once the key is declared. Here is the invented-data failure again. The fix is to make the producer supply the key or to make the consumer handle its absence, then record which.

Key in type Producer supplies it Consumer reads it Verdict
order_id Yes Yes keep, required
coupon_code Sometimes Yes, guards absence keep, NotRequired
discount_pct No Yes defect: producer must supply or consumer must stop reading
internal_note Yes No remove from boundary type, keep internal

The discount_pct row is the one that breaks consumers in production. Catching it in the table is the point of the review.

Keep runtime validation separate

TypedDict does not validate at runtime, so a boundary that receives untrusted input needs a validator beside the type. A webhook payload, a user-supplied config file, or a queue message from another system is untrusted by definition.

The validator’s job is to confirm at execution time what the TypedDict promises at the type level. Without it, a producer that sends a malformed payload passes the type check and fails wherever the consumer assumes a key exists. The Claude Code dependency install side effects guide makes a related separation between declared intent and observed runtime behavior; the same separation applies here between the annotation and the validation.

Do not present the annotation as behavior proof. The reviewer’s question is what executes, not what is written. For the complementary question of interface shape at a call site, the Python Protocols vs ABCs guide covers structural versus nominal typing. For third-party typing surfaces, the Python stub drift guide covers auditing .pyi stubs against runtime signatures.

Evidence map showing a TypedDict describing a dictionary shape while runtime validation stays a separate concern at the boundary.
Editorial evidence map based on F005 and F006. TypedDict describes a dictionary shape; it does not create values the application never supplied. Runtime validation is a separate layer.

Checklist before you merge a boundary migration

Run this list against the diff. Each row is a pass condition.

Check Pass condition If it fails
Boundary selection Type introduced only where ownership crosses a line Narrow the change to real boundaries
Key evidence Every required key traced to producer code Trace the key or mark it optional honestly
Optional keys Every NotRequired key’s absence is handled by consumers Fix the consumer or make the key required
Invented data No key added that no producer supplies Remove it or fix the producer
Static checker Checker reports the intended errors and no others Fix the type
Runtime validation Untrusted boundaries have a validator Add one before merging
Scope One boundary per commit Split the change
Workflow from loose annotation inventory through boundary selection, key evidence review, type introduction, and runtime validation check.
Editorial workflow based on F005 and F006. The sequence describes a reviewable routine; it is not an official Python typing migration command.

Worked example: a webhook payload boundary

Suppose a parser receives a payment webhook as dict[str, Any]. The external provider supplies id, amount_cents, currency, and sometimes coupon_code. A newer field receipt_url is documented by the provider but the parser never reads it.

The producer is external, the consumer is the parser module, and the pair crosses an ownership line. It qualifies as a boundary candidate. The key evidence comes from the provider’s documented payload and a captured example, not from what the parser wishes existed.

Key Evidence it is supplied Marker Note
id Provider docs + captured payload required Every event has one
amount_cents Provider docs + captured payload required Consumer arithmetic depends on it
currency Provider docs + captured payload required Consumer formats with it
coupon_code Provider docs say optional NotRequired Parser guards absence
receipt_url Provider docs, not read omit Do not add unread keys

The concrete win: a producer-side mistake that drops amount_cents now fails the static check in the producer’s own type, instead of surfacing as a formatting error in the consumer. The concrete loss: a malformed payload that passes the provider’s own validation still arrives at runtime, so the parser needs a validator regardless of the annotation. The practical implication is that the boundary type is a shared agreement, and untrusted input still needs the runtime check that the agreement cannot provide.

Working with Claude Code on the migration

Give the agent two inputs: the boundary inventory and, for each boundary, the evidence for which keys the producer supplies. Ask for one boundary type per change and for the static checker output as the verification step. The agent session works best when the check is a command that returns pass or fail, which is the shape the official best-practices guidance recommends.

Ask the agent to report three things. The type it introduced and where. The keys it marked required versus optional and the evidence for each. Any key a consumer reads that no producer supplies. A report that adds a default for absent data without evidence is wrong and should be returned.

Reviewing the key decisions is the reviewer’s job. The agent reads annotations and call sites, but whether a key’s absence is a real case or a bug is a data question. The Claude Code verification guide covers the review questions: what changed, what proves it, and what was not checked.

Tradeoff between a precise boundary type that surfaces missing keys and the runtime gap TypedDict leaves for untrusted input.
Editorial tradeoff diagram based on F005 and F006. Precision at the type level surfaces missing keys; the runtime validation gap does not close and needs its own layer.

Why converting every dictionary fails

The instinct after learning TypedDict is to annotate every dictionary in the codebase. Such an instinct produces a large diff with little value, because most dictionaries are not boundaries. A local cache keyed by string, a counter of occurrences, a set of flags assembled inside one function: none of these describes a shape two owners share.

The cost of over-conversion shows up in review. A diff that touches forty dictionaries cannot be reviewed against the data each one holds, so the reviewer either approves it unread or slows the change down. Neither outcome improves the contract. The Claude Code overengineering guide describes this pattern directly: a small request becomes a large diff when the unit of change is wrong. Here the right unit is the boundary, not the dictionary.

Over-conversion also hides the real boundaries. When every dictionary has a type, the two or three that actually cross an ownership line stop standing out. Precision that applies everywhere is precision that means nothing.

The discipline is to convert a boundary when you can name both sides: who produces the dictionary and who consumes it. If you cannot name the producer, you cannot trace a required key, and the type you write will contain at least one invented field. If you cannot name the consumer, you cannot tell which keys are truly optional. Both halves of the boundary review depend on knowing the two sides.

Dictionary kind Producer named Consumer named Convert
Webhook payload external provider parser module yes
Internal occurrence counter same function same function no
Cross-service queue message producer service consumer service yes
Local flags assembled in one call same function same function no

The two “no” rows are the discipline in practice. Leaving them as plain dictionaries keeps the boundary work focused on the pairs where a shape contract has a consumer who depends on it.

How a precise boundary surfaces a defect early

The value of a boundary type is easiest to see in the defect it catches. Suppose a producer removes currency from a payment event because a new provider version folds it into another field. With a dict[str, Any] boundary, the producer compiles, the consumer compiles, and the failure appears as a KeyError or a formatting error in the currency handler. The traceback points at the consumer.

With a TypedDict boundary where currency is required, the producer’s own code fails the static check the moment it stops supplying the key. The error appears where the edit happened, in the producer, before the change is committed. The entire benefit is moving the failure from the consumer to the producer, from runtime to check time.

The same mechanism catches the opposite direction. A consumer that starts reading receipt_url, a key the producer never sends, fails the check at the consumer because the key is not in the type. Without the boundary, the consumer would compile and fail at runtime when the key is absent. The precise type turns both directions into check-time errors at the side responsible for them.

So the review question is not “is the annotation correct” but “does each required key trace to a producer and does each read key trace to a supplier”. The annotation is a mirror of the data flow. When it is accurate, it localizes defects. When it is invented, it moves them further from the cause.

The review habits that catch these defects: Claude Code verification covers asking what changed and what proves it, and Claude Code false success covers the trap of reading a green checker as correctness. Neither substitutes for tracing a key to its producer, and both make the tracing a required part of the change rather than an optional one.

Data gap and future update

TypedDict performs no runtime validation, and this post claims no exception to that. The exact checker behavior for Required and NotRequired varies by checker and version, and the PEP and typing pages behind F005 were not full-page fetched in the research pass, so the canonical wording carries a recheck caveat.

Repository-specific data is absent: no Python version, checker version, or boundary count was inspected. A future update should verify the canonical passages and add the checker versions that support the PEP 655 markers, since that evidence was not collected here.

The post makes no benchmark, adoption, or defect-rate claim. The migration is a type-level restructure, and its effect on runtime failures is not measured in this post.

One AI API Key option for OpenAI-format agents

Claude Code uses an Anthropic-format route, so the One AI free model IDs are not a Claude Code model source. The packet records Claude IDs as unavailable on 2026-11-27.

OpenAI-format agents have a separate route: One AI API Key offers https://api.oneaiapikey.com/v1, one key, and 46 live free IDs. The route is a different client and request format, not a workaround for Claude Code authentication. Check the free model list and eligibility notes before choosing an agent route, or read the quickstart for the request shape.

FAQ

Does TypedDict validate data at runtime?

No. TypedDict describes a dictionary shape for the static checker. It does not validate values, does not create missing keys, and does not reject extra keys at execution time. A boundary that receives untrusted input needs a validator alongside the type.

Should I convert every dictionary to a TypedDict?

No. Convert dictionaries that cross an ownership line, where two modules or systems meet. A dict[str, Any] internal to one layer gains little from a type and adds surface. The boundary inventory is how you tell the two apart.

How do I decide if a key is optional?

Ask whether the data actually contains the key in every valid instance. A key the producer omits in a real case is optional. A key that should be present but is missing because of a bug is not optional, and marking it NotRequired converts the defect into a documented contract.

What if a consumer reads a key no producer supplies?

Here the problem is a defect, not a typing problem. Either the producer must supply the key or the consumer must stop reading it. Adding the key to the TypedDict silences the checker and documents data nobody sends.

Does an annotation prove the code is correct?

No. An annotation is a shared agreement about shape. It changes what the checker accepts, not what executes. Run the static checker for shape and the existing tests for behavior, and treat the two as separate evidence.

This post is one of six language and build-system guides written together. The other five cover the same shape-contract question in different settings: Python Dependency Groups vs Extras, Python Protocols vs ABCs, Python Stub Drift, Go Module Compatibility, and Go Workspace Boundaries.

A dictionary boundary is one of several generated or declared shape contracts in the batch. TypeScript Project References covers declaration ownership across projects. Protocol Buffer Reserved Fields covers a wire shape that must not be reused casually. sqlc Query Annotations covers aligning SQL with generated types, and GraphQL Code Generator Client Presets covers reviewing generated shape boundaries. C# Source Generators covers reviewing a compiler extension’s output contract, and OpenAPI Generator Customization covers tracing generated clients back to their specification inputs.

Build-system and dependency boundaries in the batch cover Gradle Constraints vs Dependencies, Gradle Capability Conflicts, Maven Optional Dependencies, and NuGet Central Package Management. Each covers a declared contract where a local choice must not be confused with what consumers receive. CMake find_package vs FetchContent covers the same ownership question in a C++ build.

On the packaging side of the same local-versus-published distinction, Python Dependency Groups vs Extras covers separating workflow requirements from consumer metadata, and Go Workspace Boundaries covers separating local development composition from published module contracts. Go Module Graph Pruning covers how indirect dependencies appear in a resolved graph, and Cargo Feature Unification covers which optional APIs a build exposes.

More Claude Code verification and review guides

Boundary work is only as good as the review that accepts it. Claude Code Verification: What to Ask for When It Says Done covers the questions to ask before calling a change finished. Claude Code False Success: Why Passing Tests Are Not Proof covers the trap of reading a green run as correctness, which is the same trap as reading an annotation as validation.

The review load a boundary migration creates: Claude Code Code Review: When Faster Generation Creates a Review Bottleneck covers what happens when generated diffs outpace review. Keeping each boundary change small is the discipline behind Claude Code Overengineering: Why Small Requests Become Large Diffs. A migration that hides a missing key behind a passing checker is the pattern Claude Code Verification asks you to break by naming what was not checked.

More from this batch

More Claude Code troubleshooting

Sources

Control checklist covering boundary selection, key evidence tracing, optional key handling, and separate runtime validation.
Editorial control checklist derived from F005 and F006. Passing the checklist shows the boundary type is honest about the data; it does not prove runtime validation, which stays a separate layer.
Verdict that precise TypedDict boundaries at ownership lines surface missing keys while runtime validation remains required for untrusted input.
Editorial verdict based on F005 and F006. Convert boundaries, not every dictionary; a precise type is a shared agreement, and untrusted input still needs a validator.
More in Blog

Try it

One API key for GPT, Grok, DeepSeek, Kimi, GLM, MiniMax, Qwen, Step, Beam, Nemotron, ERNIE, Hunyuan, Gemma, Laguna, LFM, LongCat, Llama, Solar, Jais, Mistral, K2 and Roleplay.

One AI API Key speaks the OpenAI and Anthropic formats, so you change the base URL and the key, not your code. Credit packs start at $10, and every model has a published per-token rate.

New accounts$10 credit on sign-up
Claim $10 credit →