stubpy.generator¶
stubpy.generator¶
Top-level orchestrator for a complete stub-generation run.
This module exposes two public functions:
collect_classes()— gathers classes from a loaded module in source-definition order.generate_stub()— the main entry point that sequences all pipeline stages and writes the.pyifile.
- generate_stub(filepath: str, output_path: str | None = None) str[source]¶
Generate a
.pyistub file for the Python source at filepath.Runs the full pipeline in sequence:
Load — import the source file as a live module.
Scan imports — parse AST to build a
{name: stmt}map.Build alias registry — discover type-alias sub-modules.
Collect classes — gather classes in source order.
Emit stubs — generate class and method stubs.
Assemble header — collect used
typingnames, type-module imports, and cross-file class imports.Write — write the complete
.pyito output_path.
A fresh
StubContextis created for every call, making this function fully re-entrant.- Parameters:
- Returns:
str – Full stub content as a string, identical to what is written to disk.
- Raises:
FileNotFoundError – If filepath does not exist.
ImportError – If the source file cannot be loaded as a module.
See also
stubpy.loader.load_moduleStage 1 — module loading.
stubpy.aliases.build_alias_registryStage 3 — alias discovery.
stubpy.emitter.generate_class_stubStage 5 — stub emission.
Examples
>>> from stubpy import generate_stub >>> content = generate_stub("mypackage/shapes.py") >>> content.splitlines()[0] 'from __future__ import annotations'
>>> # Write to a custom path >>> content = generate_stub( ... "mypackage/shapes.py", ... "out/shapes.pyi", ... )
- collect_classes(module: ModuleType, module_name: str) list[type][source]¶
Return all classes defined in module, sorted by source-line order.
Uses
inspect.getmembers()filtered to classes whose__module__matches module_name, so only classes defined in the file itself are included — not classes imported into it.- Parameters:
module (types.ModuleType) – The loaded module returned by
load_module().module_name (str) – Synthetic name assigned to the module by
load_module()(e.g."_stubpy_target_graphics").
- Returns:
list of type – Classes sorted by their first source line, mirroring source order.
Examples
>>> # Given shapes.py defining Shape, Circle, Rectangle in that order: >>> module, path, name = load_module("shapes.py") >>> [c.__name__ for c in collect_classes(module, name)] ['Shape', 'Circle', 'Rectangle']
Pipeline sequence
Each call to generate_stub() runs these stages in order:
generate_stub(filepath)
│
├─ 1. loader load_module() → module, path, name
├─ 2. imports scan_import_statements() → import_map
├─ 3. aliases build_alias_registry() → ctx populated
├─ 4. generator collect_classes() → sorted class list
│ └─ for each class:
│ emitter generate_class_stub()
│ └─ for each method:
│ resolver resolve_params()
│ emitter generate_method_stub()
└─ 5. generator assemble header + body → write .pyi