Functions

render(target: str | PathLike[str], *, config: Config | None = None) → StubResult[source]

Build the stub of one module without writing anything.

Parameters:
  • target (str or os.PathLike) – A .py file, an extension module (.pyd / .so), a package folder (its __init__.py is used), a glob matching exactly one file, or a dotted module name such as "mypkg.core" or "mypkg._native".

  • config (Config, optional) – Run options; defaults to Config().

Returns:

StubResult – The stub text and diagnostics. A module that fails to load gives a result with ok == False and an ERROR diagnostic instead of raising.

Raises:
  • FileNotFoundError – If target names no existing file, folder or module.

  • ValueError – If target is ambiguous, is not a Python module, or is a built-in module without a file.

See also

generate

Write the stubs of several modules.

Examples

>>> import pathlib, tempfile
>>> with tempfile.TemporaryDirectory() as folder:
...     src = pathlib.Path(folder) / "mod.py"
...     _ = src.write_text("def f(x: int) -> str: ...\n")
...     result = render(src, config=Config(imports="none"))
>>> result.ok
True
>>> print(result.text, end="")
def f(x: int) -> str: ...
generate(target: str | PathLike[str] | Iterable[str | PathLike[str]] | None = None, output: str | PathLike[str] | None = None, *, config: Config | None = None) → Report[source]

Write .pyi stubs for files, folders, globs or modules.

Parameters:
  • target (str, os.PathLike, iterable of those, or None) – What to stub: .py files, extension modules (.pyd / .so), folders (searched recursively, extension modules included), glob patterns ("src/**/*.py") or dotted module names. None uses the config’s targets and modules. An extension module found in a folder that cannot be imported (not built for this interpreter) gets a WARNING and no stub; named directly, it fails.

  • output (str or os.PathLike, optional) – Where stubs go. A path ending in .pyi is the stub of a single file target. Any other path is a stub root: each module lands at its import path beneath it (src/mypkg/core.py becomes <output>/mypkg/core.pyi) and every package gets an __init__.pyi. Defaults to config.output_dir, and without that each stub goes next to its source; there, an existing stub of an extension module is kept (it is often hand-written) unless incremental is on.

  • config (Config, optional) – Run options; defaults to Config(). With incremental=True the stub is merged into the existing file.

Returns:

Report – One StubResult per module. Modules that fail are listed in report.failed and not written; the rest of the run continues.

Raises:
  • FileNotFoundError – If a target names no existing file, folder or module.

  • ValueError – If a target is not Python source, output ends in .pyi with several targets, or no target is given or configured.

See also

check

Compare the stubs on disk without writing.

render

Build the stub of one module in memory.

Examples

>>> import pathlib, tempfile
>>> with tempfile.TemporaryDirectory() as folder:
...     src = pathlib.Path(folder) / "mod.py"
...     _ = src.write_text("def f(x: int) -> str: ...\n")
...     report = generate(src, pathlib.Path(folder) / "stubs", config=Config(imports="none"))
...     written = [p.name for p in report.written]
>>> print(report.summary())
Generated 1 stub, 0 failed.
>>> written
['mod.pyi']
check(target: str | PathLike[str] | Iterable[str | PathLike[str]] | None = None, output: str | PathLike[str] | None = None, *, config: Config | None = None) → Report[source]

Compare the stubs on disk with what generate() would write.

Nothing is written, so this suits CI and pre-commit hooks.

Parameters:
Returns:

Report – report.stale lists the stub paths that are missing or differ; report.ok is True when none are stale and none failed.

Raises:

FileNotFoundError, ValueError – As for generate().

See also

generate

Write the stubs.

Examples

>>> import pathlib, tempfile
>>> with tempfile.TemporaryDirectory() as folder:
...     src = pathlib.Path(folder) / "mod.py"
...     _ = src.write_text("def f(x: int) -> str: ...\n")
...     stubs = pathlib.Path(folder) / "stubs"
...     before = check(src, stubs, config=Config(imports="none"))
...     _ = generate(src, stubs, config=Config(imports="none"))
...     after = check(src, stubs, config=Config(imports="none"))
>>> before.ok, after.ok
(False, True)
>>> print(after.summary())
Checked 1 stub: 0 stale, 0 failed.
load_config(start: str | PathLike[str] = '.') → Config[source]

Load the nearest stubpy configuration.

Searches start and every folder above it for stubpy.toml (the whole file is the configuration; a file holding only a [tool.stubpy] table is read the same way) or a pyproject.toml with a [tool.stubpy] table. Relative targets and output_dir are resolved against the folder holding the file, so the result does not depend on the working directory.

Parameters:

start (str or os.PathLike, optional) – Folder (or file) to start the upward search from. Defaults to ".".

Returns:

Config – The file’s options over the defaults, or Config() when no file is found.

Raises:

ValueError – If the file has an unknown key or an invalid value, or is not valid TOML.

See also

find_config_file

Locate the file without reading it.

Config.from_dict

Build a config from an already parsed table.

Examples

pyproject.toml:

[tool.stubpy]
targets = ["src/mypkg"]
modules = ["mypkg._native"]
output_dir = "stubs"
imports    = "stdlib"   # or "all" / "none" / ["mypkg"]
>>> import pathlib, tempfile
>>> with tempfile.TemporaryDirectory() as folder:
...     _ = (pathlib.Path(folder) / "stubpy.toml").write_text('imports = "none"\n')
...     load_config(folder).imports
'none'
sync_docstrings(stub_path: str | PathLike[str], module: str | ModuleType | None = None, *, write: bool = True) → DocSync[source]

Copy the runtime docstrings of a module into its existing .pyi stub.

Top-level functions, classes and their methods and properties get the docstring of the matching runtime object, with binding signature lines (pybind11, Cython embedsignature, C API text signatures) removed. Only docstrings change: a body of ... becomes the docstring, an existing docstring is replaced, a one-line definition is split so the docstring opens its body, and every other byte of the file (line endings, comments, formatting, @overload variants) is kept.

Parameters:
  • stub_path (str or os.PathLike) – The hand-written stub.

  • module (str or types.ModuleType, optional) – The module to read docstrings from, as a dotted name or a module object. Defaults to None, which imports the module whose file sits next to the stub with the same stem (pkg/_x.pyx or pkg/_x.*.pyd for pkg/_x.pyi).

  • write (bool, optional) – Rewrite the stub when it changes; False only reports. Defaults to True.

Returns:

DocSync – The new text and the names whose docstrings changed.

Raises:

See also

configured_targets

The stubs and modules named in the configuration.

Examples

>>> import stubpy
>>> result = stubpy.sync_docstrings("pkg/_native.pyi")
>>> result.updated
('scale', 'Vec.norm')