generate_package

generate_package(package_dir: str | Path, output_dir: str | Path | None = None, ctx_factory: Callable[[Path, Path], StubContext] | Callable[[], StubContext] | None = None, config: StubConfig | None = None) PackageResult[source]

Generate .pyi stubs for every .py file in package_dir.

Walks package_dir recursively and calls generate_stub() for each .py source file. For every sub-directory that contains an __init__.py, the corresponding __init__.pyi is created under output_dir (if it was not already produced by generate_stub).

Files matching any pattern in config.exclude are skipped. Files that fail with an exception or ERROR-level diagnostics are recorded in PackageResult.failed and processing continues.

Parameters:
  • package_dir (str or Path) – Root of the package to process.

  • output_dir (str or Path or None) – Directory where stubs are written. The subdirectory structure of package_dir is reproduced under output_dir. When None (default), stubs are written alongside the source files.

  • ctx_factory (callable or None) –

    Called to produce a fresh StubContext for each file. Two signatures are accepted:

    • ctx_factory() — called with no arguments (backward compatible).

    • ctx_factory(source_path, output_path) — called with the absolute Path of the source .py file and the destination .pyi path, allowing per-file customisation (e.g. different execution_mode for slow modules, extra exclude patterns for generated files, custom annotation handlers).

    When None, a context derived from config (or a default config) is used.

  • config (StubConfig or None) – Configuration applied when ctx_factory is None. When both are None, StubConfig defaults are used.

Returns:

PackageResult – Contains stubs_written (success paths) and failed ((path, diagnostics) pairs for errored files).

Raises:

FileNotFoundError – If package_dir does not exist on disk.

Examples

>>> from stubpy import generate_package
>>> result = generate_package("mypackage/", "stubs/")
>>> print(result.summary())
Generated 8 stubs, 0 failed.

See also

Public API reference — overview of all public names.