stubpy.context¶
stubpy.context¶
Run-scoped mutable state for a single stub-generation pass.
Every call to generate_stub() creates a fresh
StubContext. Keeping state in a dataclass rather than
module-level globals makes the generator fully re-entrant and each
unit test independently isolated.
- class ExecutionMode(value)[source]¶
Bases:
EnumControls whether the target module is executed during stub generation.
- RUNTIME¶
Execute the module and use live objects for full introspection. This is the default and enables
**kwargsMRO back-tracing.
- AST_ONLY¶
Parse the AST only; no module execution. Safer but less precise.
- AUTO¶
Execute the module when possible; fall back to AST-only on load failures.
Controls whether the target module is executed during stub generation.
- RUNTIME¶
Execute the module and use live objects for full introspection. This is the default and enables
**kwargsMRO back-tracing.
- AST_ONLY¶
Parse the AST only; no module execution. Safer but less precise.
- AUTO¶
Execute the module when possible; fall back to AST-only on load failures.
- class StubConfig(execution_mode: ExecutionMode = ExecutionMode.RUNTIME, include_private: bool = False, respect_all: bool = True, verbose: bool = False, strict: bool = False, union_style: str = 'modern', alias_style: str = 'compatible', include_docstrings: bool = False, exclude: list[str] = <factory>, output_dir: str | None = None, infer_types_from_docstrings: bool = False, incremental_update: bool = False)[source]¶
Bases:
objectPer-run configuration options for stub generation.
All fields have sensible defaults so callers need not supply any arguments for standard usage.
- Parameters:
execution_mode (ExecutionMode) – Defaults to
RUNTIME.include_private (bool) – When
True, symbols whose names start with_are included. Defaults toFalse.respect_all (bool) – When
Trueand__all__is present, only names in__all__are stubbed. Defaults toTrue.verbose (bool) – When
True, INFO-level diagnostics are printed. Defaults toFalse.strict (bool) – When
True, any ERROR diagnostic causes a non-zero exit. Defaults toFalse.union_style (str) – Output style for union annotations.
"modern"emits PEP 604X | Ysyntax (e.g.str | None);"legacy"emitsOptional[X]/Union[X, Y]. Defaults to"modern".include_docstrings (bool) – When
True, copy the docstring from each function, method, and class into the generated stub as a literal string body instead of.... Useful when a stub doubles as quick-reference documentation without requiring the original source. Defaults toFalse.alias_style (str) –
Output format for type alias declarations.
"compatible"(default) — always emitName: TypeAlias = <rhs>using theTypeAliasannotation fromtyping. Works on all Python 3.10+ versions."pep695"— emit the Python 3.12+type Name = <rhs>soft-keyword form (PEP 695). Only use this when your project targets Python 3.12+."auto"— usepep695when running on Python 3.12+, otherwise fall back tocompatible.
exclude (list of str) – Glob patterns (relative to the package root) for files to skip during package processing. Only used by
generate_package(). Defaults to[].output_dir (str or None) – Default output directory for package processing.
Nonemeans stubs are written alongside the source files. Defaults toNone.infer_types_from_docstrings (bool) – When
True, attempt to infer parameter and return types from NumPy, Google, or Sphinx-style docstrings for functions and methods that lack explicit annotations. Inferred types are emitted as inline# type:comments rather than live annotations, making their origin clearly visible. Defaults toFalse.incremental_update (bool) – When
True, wrap the generated stub in# stubpy: auto-generated begin/endmarkers and merge it into any existing.pyifile, preserving content outside the markers. WhenFalse(default) the.pyiis overwritten completely.
- execution_mode: ExecutionMode = 'runtime'¶
- __init__(execution_mode: ExecutionMode = ExecutionMode.RUNTIME, include_private: bool = False, respect_all: bool = True, verbose: bool = False, strict: bool = False, union_style: str = 'modern', alias_style: str = 'compatible', include_docstrings: bool = False, exclude: list[str] = <factory>, output_dir: str | None = None, infer_types_from_docstrings: bool = False, incremental_update: bool = False) None¶
- class AliasEntry(annotation: Any, alias_str: str)[source]¶
Bases:
NamedTupleA pairing of a live annotation object with its stub alias string.
Examples
>>> entry = AliasEntry(annotation=str | float | int, alias_str="types.Length") >>> entry.alias_str 'types.Length'
- class StubContext(alias_registry: list[AliasEntry] = <factory>, type_module_imports: dict[str, str]=<factory>, used_type_imports: dict[str, str]=<factory>, config: StubConfig = <factory>, diagnostics: DiagnosticCollector = <factory>, symbol_table: Any | None = None, all_exports: set[str] | None = None, module_namespace: dict[str, ~typing.Any]=<factory>)[source]¶
Bases:
objectMutable state container scoped to one stub-generation run.
Create one instance per
generate_stub()call, or pass a pre-configured instance to supply custom options.- alias_registry¶
Registered type aliases from imported sub-modules.
- Type:
list of AliasEntry
- config¶
Per-run options (execution mode, privacy, verbosity, etc.).
- Type:
- diagnostics¶
Accumulated warnings and errors from the pipeline.
- Type:
- symbol_table¶
Populated after the symbol-table stage;
Noneuntil then.- Type:
SymbolTable or None
- module_namespace¶
The full
__dict__of the loaded module, populated after stage 1 (module loading). Used byresolve_function_params()to look up forwarding-target callables by name. Empty in AST-only mode.- Type:
Examples
>>> ctx = StubContext() >>> ctx.diagnostics.summary() '0 errors, 0 warnings, 0 infos' >>> ctx.config.execution_mode.value 'runtime' >>> ctx.symbol_table is None True
Mutable state container scoped to one stub-generation run.
Create one instance per
generate_stub()call, or pass a pre-configured instance to supply custom options.- config¶
StubConfig— per-run options (execution mode, privacy, etc.).
- diagnostics¶
DiagnosticCollector— accumulated issues.
- symbol_table¶
SymbolTableorNone— populated after the symbol-table stage.
- all_exports¶
set[str]orNone— contents of__all__, when present.
- alias_registry¶
List of
AliasEntry— registered type aliases from sub-modules.
- type_module_imports¶
dict[str, str]— import statements keyed by local alias name.
- used_type_imports¶
dict[str, str]— subset of type_module_imports actually used.
- lookup_alias(annotation: Any) str | None[source]¶
Return the alias string for annotation if registered, else
None.Examples
>>> ctx = StubContext() >>> ctx.alias_registry.append(AliasEntry(str | int, "types.T")) >>> ctx.type_module_imports["types"] = "from pkg import types" >>> ctx.lookup_alias(str | int) 'types.T' >>> ctx.lookup_alias(str | float) is None True
- lookup_alias(annotation: Any) str | None[source]¶
Return the alias string for annotation if registered, else
None.Examples
>>> ctx = StubContext() >>> ctx.alias_registry.append(AliasEntry(str | int, "types.T")) >>> ctx.type_module_imports["types"] = "from pkg import types" >>> ctx.lookup_alias(str | int) 'types.T' >>> ctx.lookup_alias(str | float) is None True
- __init__(alias_registry: list[AliasEntry] = <factory>, type_module_imports: dict[str, str]=<factory>, used_type_imports: dict[str, str]=<factory>, config: StubConfig = <factory>, diagnostics: DiagnosticCollector = <factory>, symbol_table: Any | None = None, all_exports: set[str] | None = None, module_namespace: dict[str, ~typing.Any]=<factory>) None¶
Notes
StubContext is the central state carrier for one stub-generation
run. A fresh instance is created inside every call to
generate_stub(), making the generator fully
re-entrant.