generate_stub

generate_stub(filepath: str, output_path: str | None = None, ctx: StubContext | None = None) str[source]

Generate a .pyi stub file for the Python source at filepath.

A fresh StubContext is created when ctx is None, making this function fully re-entrant. Pass an explicit ctx to supply custom StubConfig options (e.g. include_private=True, execution_mode=ExecutionMode.AST_ONLY) or to inspect diagnostics after the call.

Execution modes

RUNTIME (default)

Execute the module; full introspection available.

AST_ONLY

Parse the AST only — no module execution. Safer for modules with import-time side effects; live types will be None.

AUTO

Execute when possible; fall back to AST-only on load failure.

param filepath:

Path to the .py source file.

type filepath:

str

param output_path:

Where to write the .pyi file. Defaults to the same directory and stem as filepath with a .pyi extension.

type output_path:

str, optional

param ctx:

Pre-configured context. Created fresh when None.

type ctx:

StubContext, optional

returns:

str – Full stub content as a string, identical to what is written to disk.

raises FileNotFoundError:

If filepath does not exist.

raises ImportError:

If the source file cannot be loaded as a module (RUNTIME mode only; AUTO mode falls back to AST-only instead of raising).

See also

generate_package

Batch generation for a whole package directory.

stubpy.loader.load_module

Stage 1 — module loading.

stubpy.ast_pass.ast_harvest

Stage 2 — AST pre-pass.

stubpy.symbols.build_symbol_table

Stage 5 — symbol table.

stubpy.emitter.generate_class_stub

Class stub emission.

stubpy.emitter.generate_function_stub

Function stub emission.

stubpy.emitter.generate_variable_stub

Variable stub emission.

stubpy.emitter.generate_alias_stub

Alias/TypeVar stub emission.

stubpy.emitter.generate_overload_group_stub

Overload group stub emission.

See also

Public API reference — overview of all public names.