stubtest tool automatically checks for discrepancies between stub files and the actual implementation at runtime. It helps ensure stub files stay synchronized with the code they describe.
What stubtest does
Stubtest will:- Import your code and introspect it at runtime using the
inspectmodule - Analyze stub files using mypy
- Compare the two and report differences
- Check for missing definitions, incorrect signatures, and type mismatches
Stubtest is used to test Python’s official collection of library stubs, typeshed.
What stubtest doesn’t do
Stubtest has limitations:- No static analysis: It relies only on runtime introspection
- Limited visibility: Can’t verify return types or internal implementation
- Can’t type check: Use
mypyfor type checking - Can’t generate stubs: Use
stubgenorpyright --createstubinstead - Can’t infer from tests: Use
monkeytypefor runtime-based stub generation
Basic usage
Command options
Module or package name to test against stubs.
Show help message and exit.
Make stubtest’s output more concise, one line per error.Default:
false (detailed output)Ignore errors for stubs missing things that are present at runtime.Default:
falseIgnore errors for whether an argument should or shouldn’t be positional-only.Default:
falseUse FILE as an allowlist. Can be passed multiple times to combine allowlists.Allowlists support regular expressions. Entries in the allowlist suppress corresponding errors.
Print an allowlist (to stdout) to be used with
--allowlist.Useful for silencing all existing errors when introducing stubtest to an existing project.Default: falseIgnore unused allowlist entries.Without this, stubtest complains if an allowlist entry isn’t necessary.Default:
falseUse specified mypy config file to determine mypy plugins and mypy path.
Use the custom typeshed in DIR.
Check all stdlib modules in typeshed.Default:
falseExamples
Allowlist format
Allowlist files support:- One entry per line: Each line specifies an error to ignore
- Comments: Lines starting with
# - Regular expressions: For matching multiple errors
- Optional patterns: Use
(pattern)?for conditional suppression
allowlist.txt
Example workflow
Here’s a complete example showing stubtest in action:Source code
library.py
Stub file
library.pyi
Running stubtest
Output
Integration with CI
Stubtest works well in continuous integration:.github/workflows/stubtest.yml
Best practices
Common error types
Stubtest reports various types of inconsistencies:- Missing definitions: Stub doesn’t include something from runtime
- Extra definitions: Stub includes something not in runtime
- Signature mismatches: Parameters, defaults, or return types differ
- Type mismatches: Variable types don’t match
- Positional-only differences: Arguments marked incorrectly
- Class hierarchy differences: Base classes or metaclasses differ