Skip to navigation

Python Stub Drift: Audit Third-Party Types With Claude Code

In short: Find mismatches between Python stubs and runtime signatures before accepting a third-party typing change.

Published 20 min read
On this page

Direct answer

A stub drifts when its .pyi signature no longer matches the runtime API it describes, and the drift is invisible to a normal type check because the checker trusts the stub. Audit it in two stages: a static signature inventory first, then an executable comparison only in an environment you have approved. The caution that drives the staging is specific. mypy documents stubtest as a tool for checking stubs against runtime objects and warns that it imports and executes the checked packages. Which makes stubtest an approved-environment tool, not a command to run against an arbitrary dependency. The concrete win is a recorded list of signatures that differ, so a typing change is accepted on evidence rather than on trust. The concrete loss is that stub parity says nothing about behavior; a stub that matches every signature can still describe a function that does something different at runtime.

Ask Claude Code to build the static inventory and the diff table. Do not ask it to run stubtest as a first step, and do not ask it to edit a third-party stub before checking who owns the file.

Why drift is expensive to find late

Stubs are a promise about a library’s surface. When the runtime changes and the stub does not, every caller that trusts the stub is working from stale information. The failure lands as a runtime error in code that the checker called clean, which is the worst place to find it because the check gave a green result.

The cost is the gap between the green check and the failing runtime. A team that accepts a stub update on trust has no record of what changed, so a break becomes a debugging session. A team that records the signature diff has a reviewable list and can decide which differences matter before the update ships.

There is a trust angle too. A stub is a third-party artifact. Editing it locally is a change to a file somebody else owns, and the fix may belong upstream. The audit’s job is to produce evidence, not to patch the stub in place.

Evidence and its limits

Official, F007: mypy documents stubtest as a tool for checking stubs against runtime objects and warns that it imports and executes the checked packages. The warning is specific to stubtest and is not a general claim about static type checking. The stub files page documents how stubs relate to the packages they describe, and the typeshed README covers stub ownership for third-party packages.

Official, agent loop: Claude Code best practices recommends a check that returns pass or fail. In a stub audit the static stage is the inventory diff; the executable stage is stubtest in an approved environment.

Derived, F008: Beginning with a static signature inventory and using executable comparison only in an approved environment is a risk-aware workflow recommendation. It is not an official mypy requirement.

No claim is made that stub parity proves application correctness, and no runtime behavior is inferred from type hints.

Why stubs drift

Three causes account for most drift. A library adds a parameter with a default, and the stub keeps the old signature. A library renames or removes a public function, and the stub still exports the old name. A library changes a return type in a way the stub does not reflect.

Every one of these causes is quiet because the checker trusts the stub. A static check that reads the stub reports the stub’s version of the world. The runtime disagrees, and nothing in the ordinary loop notices until a caller hits the difference at execution time.

Cause Stub shows Runtime does Effect on callers
Added optional parameter old arity accepts extra argument callers unaware of the new option
Removed or renamed function old name present attribute missing runtime AttributeError
Changed return type old type new type wrong downstream usage assumed safe

The first row is benign and common. The second and third are the ones that break code the checker called clean, and they are the ones the audit should catch.

Read stub ownership

Before comparing anything, determine who owns the stub. A stub can live in the library itself, in typeshed, or in a local stubs/ directory the project maintains. Ownership decides where a fix belongs.

The typeshed project maintains stubs for many third-party packages, and the typeshed README describes that arrangement. A stub that lives in typeshed is fixed upstream. A stub that ships inside a package is the package author’s. A stub your project overrides is yours, and that override is the thing to keep reviewable.

bash
  # locate stubs for a package
python -c "import importlib.util,os; s=importlib.util.find_spec('TARGET'); print(s.origin)"
# typeshed and local overrides
rg --files . | rg "\.pyi$" | head -50

Do not modify a third-party stub without checking ownership. A local edit to a typeshed-owned stub is lost on the next stub update, and it hides the real gap from whoever maintains the file. The fix belongs in a report upstream or in a documented override.

Compare signatures statically

The static stage is a read-only inventory. Each public symbol in the stub needs its signature recorded, alongside the runtime object, record the signature from introspection or from the source. Put the two side by side.

bash
  # runtime signature without importing as a side-effect-free step is not guaranteed;
# prefer reading source for the static stage
rg -n "^def |^class " path/to/package/*.py

A source read is the safer static step because it does not execute the package. Put the differences in a table with the symbol, the stub signature, the runtime signature, and the difference.

Symbol Stub signature Runtime signature Difference Severity
connect (host, port) (host, port, timeout=5) added optional param low
parse (raw: str) -> Node (raw: bytes) -> Node parameter type changed medium
load_all present absent removed upstream high
Result.items list[Item] tuple[Item, ...] return type changed medium

Severity is a review judgment, not a tool output. A removed symbol is high because it breaks callers at runtime. A changed return type is medium because downstream code may assume the old shape. An added optional parameter is low.

Claude Code can draft this table by reading the stub and the source, and the draft needs review. The agent reads text; it does not execute the package during the static stage, which is the point. The Claude Code verification guide covers asking what changed and what proves it. A draft table with no runtime column is incomplete.

Understand stubtest

stubtest is mypy’s executable comparison tool. It checks a stub against the runtime objects and reports mismatches. The documentation is explicit that it imports and executes the packages it checks. The fact puts it in the second stage.

Because it executes code, stubtest runs whatever a package runs at import time: module-level statements, configuration, and any side effects the import triggers. Running it against an arbitrary dependency in a production or shared environment is the specific risk to avoid. The Claude Code dependency install side effects guide covers what an install or import can do beyond adding files; the same caution applies to a tool that imports the package it inspects.

Stage Tool Executes package Where to run
Static inventory source read No Anywhere
Executable comparison stubtest Yes Approved environment only

Treat the table as the staging rule. The static stage is safe everywhere. The executable stage is not, and it needs an environment whose behavior you accept.

Plan an isolated stub audit

Run stubtest against one package, in an environment built for the purpose, with the versions you intend to audit. Write down the command, the package version, and the output.

bash
# illustrative shape only; confirm current flags in the mypy docs
python -m mypy.stubtest TARGET_PACKAGE --mypy-config-file mypy.ini 2> stubtest-report.txt

Do not run this against every dependency in one pass, and do not run it in a shared or production environment. One package at a time keeps the report readable and the blast radius small. The report is the executable counterpart to the static table: it confirms which differences are real at runtime and may surface differences the source read missed.

Note what the executable stage adds. A difference the static table predicted and stubtest confirms is settled. A difference only stubtest finds is a reminder that the source read is not complete. A difference the static table predicted that stubtest does not report is worth a second look, because the runtime may have a dynamic attribute the source does not show.

Record missing types

Drift is not only wrong signatures. It is also missing stubs. A package with no stub, or with a partial stub, leaves callers without a shape contract for part of its surface. List which public symbols have no stub entry.

A missing entry is a gap, not a defect in the stub. Whether it matters depends on whether your code uses that part of the surface. The Python TypedDict boundaries guide covers the complementary case where a shape exists but is too loose; a missing stub entry is the case where the shape does not exist at all.

Public symbol Stub entry Used by your code Action
connect present Yes compare signatures
legacy_helper absent No record gap, no action
parse_stream absent Yes file upstream or add a local override

The second row is the discipline: a gap in an unused part of the surface is a note, not a task. Filing an upstream report for a symbol nobody calls is wasted effort.

Review the stub diff

When a stub update arrives, review it as a contract change. The diff tells you what the stub now claims. The audit tells you whether the runtime agrees. Accept the update when the two match, and file the differences that do not.

The concrete win in this workflow is a reviewable record. A team that keeps the static table and the stubtest report can answer, for any accepted typing change, exactly which signatures changed and which were confirmed at runtime. The concrete loss is the execution cost: the static stage is safe but incomplete, and the executable stage is complete but runs code, so it is confined to an approved environment. There is no free stage that is both complete and side-effect-free.

The practical implication is that a stub is an owned artifact with an upstream home, and an audit is a report to that home rather than a local patch. Teams that treat stubs as editable local files accumulate overrides that drift from upstream and hide the real gaps.

Evidence map showing a stub signature diverging from the runtime API and the two-stage audit separating a source read from executable stubtest.
Editorial evidence map based on F007 and F008. mypy’s stubtest documentation warns that the tool imports and executes the packages it checks, which is why the executable stage is confined to an approved environment.

Checklist before accepting a typing change

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

Check Pass condition If it fails
Ownership Stub owner identified before any edit Check typeshed or package origin
Static inventory Symbol table complete for used surface Finish the read
Diff table Every difference has stub and runtime columns Complete the table
Severity Each difference has a recorded severity judgment Review severity
Executable stage stubtest ran on one package in an approved env Do not run it broadly
Report kept stubtest output stored beside the static table Save the report
Upstream path Differences filed or documented as overrides File the report upstream
Workflow from ownership check through static inventory, difference table, isolated stubtest run, and upstream report.
Editorial workflow based on F007 and F008. The sequence is a risk-aware recommendation, not an official mypy requirement, and the executable stage runs code.

Worked example: one package, two stages

Suppose a dependency updates and the project pins the new version. The static stage reads the stub and the source for the two symbols the project uses.

Symbol Stub now claims Source shows Difference Stage 2 result
client.connect (host, port) (host, port, timeout=5) added optional param confirmed by stubtest
client.parse (raw: str) (raw: bytes) parameter type changed confirmed by stubtest
client.load_all present absent removed upstream confirmed missing at runtime

The third row is the one that would have broken production. A caller using load_all would fail at runtime with an AttributeError while the checker reported the stub’s version of the world. The audit catches it before the update ships.

The honest gap: the two-stage record covers the symbols the project uses and the surface stubtest reached. Symbols the project never calls are not audited, and a dynamic attribute the source does not show may still escape both stages. Write that scope down rather than calling the audit complete.

Working with Claude Code on the audit

Give the agent three inputs: the package name and version, the symbols your code uses, and the approved environment for the executable stage. Ask for the static table first and the stubtest report second. 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 static difference table with both columns. The stubtest command it ran and the environment. Any symbol your code uses that has no stub entry. A report that runs stubtest as the first step, or that edits a third-party stub without checking ownership, should be returned.

Reviewing the severity column is the reviewer’s job. The agent reads signatures, but whether a changed return type breaks a caller is a call-site question. The Claude Code overengineering guide describes how a small audit request can produce a large diff; keep the audit read-only and keep stub edits out of it unless the stub is locally owned.

Tradeoff between a safe but incomplete source read and a complete but executing stubtest stage confined to an approved environment.
Editorial tradeoff diagram based on F007 and F008. The static stage is side-effect-free but incomplete; the executable stage is complete but imports code, so it needs an approved environment.

Common drift patterns and how to spot them

Four patterns account for most stub drift, and each has a detection method that works at the static stage. Naming them makes the inventory faster because each one points at a specific thing to compare.

The first is the added parameter with a default. A library adds timeout=5 to a function and the stub keeps the two-parameter form. Callers still work, so the drift is benign, but the stub no longer describes the surface a new caller can use. Detection is an arity comparison between the stub signature and the source signature.

The second is the removed or renamed export. A library renames load_all to load and the stub still exports the old name. This is the pattern that breaks callers at runtime with an AttributeError, because the checker reports the stub’s version of the world. Detection is a symbol-existence comparison for every name the project imports.

The third is the changed type. A parameter moves from str to bytes, or a return type widens. The stub and the source disagree about the type, and downstream code that trusted the stub now makes a wrong assumption. Detection is a per-symbol type comparison, which is the slowest part of the inventory because it cannot be automated from names alone.

The fourth is the missing stub entry. A public symbol exists at runtime with no stub declaration. Detection is a symbol-existence comparison in the other direction: runtime symbols the stub does not mention.

Pattern Stub shows Runtime shows Detection
Added optional parameter old arity extra default param arity comparison
Removed export old name absent symbol existence
Changed type old type new type per-symbol type diff
Missing entry absent present reverse symbol existence

The second row is the highest severity because it produces a runtime failure the checker called clean. The fourth row is a gap rather than a defect, and it matters only if the project uses that part of the surface.

Claude Code can run the first, second, and fourth checks mechanically by reading the stub and the source and comparing names and arities. The third check, a per-symbol type comparison, is where the agent’s output needs the most review, because two types can look equivalent and behave differently, and a named type with the same structure is not always substitutable.

Why a green type check does not clear the stub

A normal type check reads the stub and reports on the project’s code against it. It never compares the stub to the runtime. So a green check is silent about drift: the check and the drift are on opposite sides of the stub.

This is the trap the two-stage audit exists to avoid. A team that accepts a stub update because the type check passes has verified the project against a claim, not the claim against reality. The static inventory is the first comparison against reality, and the executable stage is the second. Neither is the ordinary type check.

The same shape of mistake appears elsewhere in this batch. A boundary annotation that documents invented keys is a claim nobody verified against the data. A version tag applied before the compatibility classification is a claim nobody verified against the change. In each case the visible artifact is trusted instead of the thing it describes, and the review exists to break that trust deliberately.

For the review habits that catch this, Claude Code verification covers asking what a green result does and does not prove, and Claude Code false success covers the general trap of reading a passing check as correctness. A stub audit that ends at the type check has not started.

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

A stub is a declared surface, and the batch covers other declared surfaces with their own drift risks. Go Module Compatibility covers a declared import-path contract that must not change silently. Protocol Buffer Reserved Fields covers a declared wire contract. TypeScript Project References covers declared declaration output across projects, and Go Module Graph Pruning covers the declared requirement graph.

Interface and shape contracts in the batch cover Python Protocols vs ABCs, Python TypedDict Boundaries, and Gradle Variant Attributes. All of them cover a contract where two sides must agree about which shape is in force.

Build-system and dependency boundaries cover Cargo Feature Unification, Gradle Constraints vs Dependencies, NuGet Central Package Management, and CMake find_package vs FetchContent. All of them cover a declared dependency surface where a declared intent and an observed resolution can diverge.

Generated-surface work in the batch covers C# Source Generators, sqlc Query Annotations, OpenAPI Generator Customization, and GraphQL Code Generator Client Presets. All of them cover a surface that must be reviewed against its inputs rather than accepted because it compiles.

More Claude Code verification and review guides

An audit is only as good as the review that acts on it. Claude Code Verification: What to Ask for When It Says Done covers the questions to ask before accepting an agent’s report. Claude Code False Success: Why Passing Tests Are Not Proof covers the trap of reading a green check as correctness, which is the trap this audit exists to avoid. A static table with no executable confirmation is a green result that proves less than it appears to.

The review load an audit creates: Claude Code Code Review: When Faster Generation Creates a Review Bottleneck covers what happens when generated evidence outpaces review. Keeping the audit read-only until the diff is accepted is the discipline behind Claude Code Overengineering: Why Small Requests Become Large Diffs. Splitting the audit from any fix it produces keeps each change independently reviewable.

Data gap and future update

The execution warning behind F007 is specific to stubtest and is quoted from the mypy documentation. This post does not claim a general execution property for static type checking, and it does not claim that any particular stubtest flag set is complete. The stub files page and the typeshed README were reachable at research time, but detailed flag coverage was not extracted.

The post makes no benchmark, coverage, or defect-rate claim. The audit workflow is derived from the documented distinction between static checking and executable comparison. A future update should verify the current stubtest flag set and add the mypy version behind the execution warning, since that evidence was not collected here.

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 use the cost calculator to compare hosted options.

FAQ

Is it safe to run stubtest on any dependency?

No. mypy’s documentation warns that stubtest imports and executes the packages it checks. Run it against one package at a time, in an environment built for the purpose, with versions you intend to audit. The static inventory stage is the safe first step.

Does matching stubs prove my application is correct?

No. Stub parity means the stub’s signatures match the runtime’s signatures. It says nothing about what those functions do. A stub that matches every signature can still describe a function with different behavior.

Can I infer runtime behavior from type hints?

No. Type hints describe shapes, not behavior. This post does not infer runtime behavior from hints, and the audit is limited to signature differences that are visible in the stub and the source or confirmed by stubtest.

Should I edit a third-party stub to fix a gap?

Check ownership first. A stub in typeshed or inside a package is fixed upstream, and a local edit is lost on the next update and hides the gap. File the difference upstream or document a local override deliberately.

What if the static table and stubtest disagree?

Treat the disagreement as a finding, not a bug in the process. stubtest executes the package and can see dynamic attributes a source read misses. Investigate the difference before accepting the typing change, and record what the executable stage added.

More from this batch

More Claude Code troubleshooting

Sources

Control checklist covering stub ownership, static inventory, difference table, isolated stubtest run, and upstream reporting.
Editorial control checklist derived from F007 and F008. Passing the checklist shows the audit was staged honestly; it does not prove application correctness or full surface coverage.
Verdict that a two-stage audit produces a reviewable signature diff while stub parity still does not prove runtime behavior.
Editorial verdict based on F007 and F008. The audit records which signatures differ and which the executable stage confirmed; it never converts stub parity into a behavior guarantee.
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 →