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
.pyfile, an extension module (.pyd/.so), a package folder (its__init__.pyis 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 == Falseand 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
generateWrite 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
.pyistubs for files, folders, globs or modules.- Parameters:
target (str, os.PathLike, iterable of those, or None) – What to stub:
.pyfiles, extension modules (.pyd/.so), folders (searched recursively, extension modules included), glob patterns ("src/**/*.py") or dotted module names.Noneuses the config’stargetsandmodules. 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
.pyiis 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.pybecomes<output>/mypkg/core.pyi) and every package gets an__init__.pyi. Defaults toconfig.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) unlessincrementalis on.config (Config, optional) – Run options; defaults to
Config(). Withincremental=Truethe stub is merged into the existing file.
- Returns:
Report – One
StubResultper module. Modules that fail are listed inreport.failedand 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
.pyiwith several targets, or no target is given or configured.
See also
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:
target (str, os.PathLike, iterable of those, or None, optional) – What to check; as for
generate().output (str or os.PathLike, optional) – Where the stubs live; as for
generate().config (Config, optional) – Run options; defaults to
Config().
- Returns:
Report –
report.stalelists the stub paths that are missing or differ;report.okisTruewhen none are stale and none failed.- Raises:
FileNotFoundError, ValueError – As for
generate().
See also
generateWrite 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 apyproject.tomlwith a[tool.stubpy]table. Relativetargetsandoutput_dirare 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_fileLocate the file without reading it.
Config.from_dictBuild 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
.pyistub.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,@overloadvariants) 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.pyxorpkg/_x.*.pydforpkg/_x.pyi).write (bool, optional) – Rewrite the stub when it changes;
Falseonly reports. Defaults toTrue.
- Returns:
DocSync – The new text and the names whose docstrings changed.
- Raises:
FileNotFoundError – If the stub does not exist.
ImportError – If the module cannot be found or imported.
See also
configured_targetsThe stubs and modules named in the configuration.
Examples
>>> import stubpy >>> result = stubpy.sync_docstrings("pkg/_native.pyi") >>> result.updated ('scale', 'Vec.norm')