Configuration¶
- class Config(imports: str | tuple[str, ...]='all', deny_imports: tuple[str, ...]=(), import_timeout: float = 300.0, isolate: bool = False, include_private: bool = False, respect_all: bool = True, include_docstrings: bool = False, infer_types: bool = False, incremental: bool = False, resolve_kwargs: bool = True, resolve_args: bool = True, union_style: UnionStyle = UnionStyle.MODERN, alias_style: AliasStyle = AliasStyle.COMPATIBLE, version_branches: VersionBranches = VersionBranches.EMIT, exclude: tuple[str, ...]=('.*', '__pycache__', 'build', 'dist', '.venv', 'venv', '*.egg-info', '.git', '.tox', '.nox', '<non-identifier>'), extend_exclude: tuple[str, ...]=<factory>, output_dir: str | None = None, typecheck: bool = False, prune: bool = False, cache: bool = False, cache_dir: str = '.stubpy_cache', stub_package: bool = False, targets: tuple[str, ...]=<factory>, modules: tuple[str, ...]=<factory>, verbose: bool = False, strict: bool = False, array_metadata: bool = False, target_python: str = '3.10', docstrings: DocstringTargets = DocstringTargets(packages=(), import_root=None, overrides=()))[source]¶
Bases:
objectOptions for one stubpy run.
Every field has a default, so
Config()is a valid configuration. Instances are immutable; usereplace()to derive a changed copy. Enum fields also accept their string values (union_style="legacy"). Pass one torender(),generate()orcheck(), or read it from a file withload_config(). Pass one torender(),generate()orcheck(), or read it from a file withload_config().- Parameters:
imports (str or sequence of str) – Which modules stubpy may import (execute):
"all"(the default),"none"(source analysis only, nothing is executed),"stdlib", or a list of dotted names (pkgorpkg.*, each with its submodules) allowed on top of the standard library. A target whose import is blocked, directly or through one of its imports, is stubbed from its source with an INFO. This limits import-time side effects; it is not a security sandbox.deny_imports (sequence of str) – Dotted names (
pkgorpkg.*) never imported, whatever imports allows. Defaults to none.import_timeout (float) – Seconds one module may take to import. A longer import (a module waiting for input, the network or a lock, or looping forever) stops the run with exit code 2 and the stack of every thread.
0disables the limit. Defaults to300.0.isolate (bool) – Import each module in a child process first; a module whose child does not finish within import_timeout is stubbed from its source with a WARNING and the run goes on. Each module is imported twice, so runs are slower. No effect on Pyodide. Defaults to
False.include_private (bool) – Stub names that start with
_. Defaults toFalse.respect_all (bool) – When a module defines
__all__, stub only the public names it lists. Defaults toTrue.include_docstrings (bool) – Use each symbol’s docstring as its stub body instead of
.... Defaults toFalse.infer_types (bool) – Fill in missing parameter and return types from NumPy, Google or Sphinx docstrings. Defaults to
False. Safe return types and the docstring types of forwarded keywords are inferred either way.incremental (bool) – Wrap the generated stub in
# stubpy: auto-generated begin/endmarkers and merge it into an existing.pyi, keeping manual edits outside the markers. Defaults toFalse.resolve_kwargs (bool) – Expand
**kwargsinto the parameters it is forwarded to. Defaults toTrue.resolve_args (bool) – Expand
*argsinto the positional parameters it is forwarded to. Defaults toTrue.union_style (UnionStyle or str) –
"modern"(X | None) or"legacy"(Optional[X]). Defaults to"modern".alias_style (AliasStyle or str) –
"compatible"(X: TypeAlias = ...),"pep695"(type X = ...) or"auto". Defaults to"compatible".version_branches (VersionBranches or str) –
"emit"copiesif sys.version_info .../if sys.platform ...blocks into the stub with every branch;"resolve"keeps only the branch the running interpreter takes. Defaults to"emit".exclude (sequence of str) – Patterns of files and folders a folder run skips; setting it replaces the defaults (hidden names
.*,__pycache__,build,dist,.venv,venv,*.egg-info,.git,.tox,.noxand<non-identifier>, any folder or module name Python cannot import). A pattern with/matches the path relative to the folder target, one without matches any single name. Files named directly are never skipped.extend_exclude (sequence of str) – More patterns, added to exclude.
output_dir (str or None) – Stub root used when
generate()gets nooutput;Nonewrites each stub next to its source.prune (bool) – After a run over a folder, remove (
generate) or report as stale (check) the.pyifiles under its stub tree that no module produced, such as stubs left behind by a moved or deleted module. Stubs tracked by git are never touched. Defaults toFalse.typecheck (bool) – Type-check the written stubs with mypy (or pyright, when mypy is not installed) and report each error as a WARNING on its stub. Defaults to
False.cache (bool) – Reuse the stub of a module whose source, and the sources of the package modules it imports, are unchanged since the last run with the same options, stubpy and Python. Defaults to
False.cache_dir (str) – Folder of the run cache. Defaults to
".stubpy_cache"(relative to the working folder).stub_package (bool) – Write each top-level package as a PEP 561 stub-only distribution
<output>/<pkg>-stubs/(apyproject.tomland the<pkg>-stubspackage with a partialpy.typed). Needs an output folder. Defaults toFalse.targets (sequence of str) – Paths, folders or globs to act on when no target is given.
modules (sequence of str) – Dotted module names to act on when no target is given.
verbose (bool) – Report INFO diagnostics on the command line. Defaults to
False.strict (bool) – Count WARNING diagnostics as failures. Defaults to
False.docstrings (DocstringTargets or mapping) – The
[tool.stubpy.docstrings]table: the hand-written stubsstubpy docstringssyncs when given no STUB.array_metadata (bool) – Keep the shape, order and device of nanobind arrays:
ndarray[dtype=float32, shape=(*, 3), order='C']becomesAnnotated[NDArray[float32], dict(shape=(None, 3), order='C')], as nanobind’s own stub generator writes it. Defaults toFalse(a plainNDArray).target_python (str) – Oldest Python (
"3.10") the stubs must import on:typingnames added later (Self,override,TypeIs,deprecated, …) are imported fromtyping_extensions. Defaults to"3.10".
- Raises:
ValueError – If an enum field gets an unknown value.
TypeError – If a flag is not a
boolor a list field is not a list of strings.
See also
load_configRead a configuration from
stubpy.tomlorpyproject.toml.Config.from_dictBuild a configuration from a mapping.
Examples
>>> cfg = Config(imports="none", include_private=True) >>> cfg.may_import False >>> cfg.replace(union_style="legacy").union_style.value 'legacy'
- union_style: UnionStyle = 'modern'¶
- alias_style: AliasStyle = 'compatible'¶
- version_branches: VersionBranches = 'emit'¶
- exclude: tuple[str, ...] = ('.*', '__pycache__', 'build', 'dist', '.venv', 'venv', '*.egg-info', '.git', '.tox', '.nox', '<non-identifier>')¶
- docstrings: DocstringTargets = DocstringTargets(packages=(), import_root=None, overrides=())¶
- classmethod from_dict(data: Mapping[str, Any]) Config[source]¶
Build a config from a mapping such as a
[tool.stubpy]table.Keys are field names; dashes are read as underscores.
- Parameters:
data (mapping) – Option names to values.
- Returns:
Config – The options over the defaults.
- Raises:
ValueError – On an unknown key (with the closest valid name) or an invalid value.
See also
load_configRead the mapping from a configuration file.
Examples
>>> Config.from_dict({"include-private": True, "imports": "stdlib"}).imports 'stdlib'
- property exclude_patterns: tuple[str, ...]¶
excludefollowed byextend_exclude, as a tuple of patterns.
- property import_policy: ImportPolicy¶
The
ImportPolicyofimportsanddeny_imports.
- replace(**changes: Any) Config[source]¶
Return a copy with changes applied and validated.
- Parameters:
**changes – Field names and their new values, as accepted by
Config.- Returns:
Config – A new configuration; the original is unchanged.
- Raises:
TypeError – If a name is not a field, or a value has the wrong type.
ValueError – If an enum field gets an unknown value.
See also
Config.from_dictBuild a configuration from a mapping.
Examples
>>> Config().replace(include_private=True).include_private True
The style enums are the types of the union_style and alias_style fields. They are not
exported at the top level; import them from stubpy.config, or pass the plain strings.
- class UnionStyle(*values)[source]¶
Bases:
_ChoiceHow unions are written.
- Variables:
MODERN – PEP 604:
int | None. The default.LEGACY –
Optional[int]andUnion[int, str].
Examples
>>> UnionStyle("legacy") is UnionStyle.LEGACY True >>> str(UnionStyle.MODERN) 'modern'
- MODERN = 'modern'¶
- LEGACY = 'legacy'¶
- class AliasStyle(*values)[source]¶
Bases:
_ChoiceHow type aliases are written.
- Variables:
COMPATIBLE –
Name: TypeAlias = rhs. The default.PEP695 –
type Name = rhs(readable by Python 3.12+ tools).AUTO –
PEP695when stubpy runs on Python 3.12+, elseCOMPATIBLE.
Examples
>>> AliasStyle("pep695") is AliasStyle.PEP695 True >>> str(AliasStyle.COMPATIBLE) 'compatible'
- COMPATIBLE = 'compatible'¶
- PEP695 = 'pep695'¶
- AUTO = 'auto'¶
- class VersionBranches(*values)[source]¶
Bases:
_ChoiceWhat happens to
ifstatements testingsys.version_infoorsys.platform.- Variables:
EMIT – Copy the
if/elif/elseinto the stub, each branch with the stubs of the names it defines, as typeshed does. The default.RESOLVE – Keep only the branch the running interpreter takes.
Examples
>>> VersionBranches("resolve") is VersionBranches.RESOLVE True >>> str(VersionBranches.EMIT) 'emit'
- EMIT = 'emit'¶
- RESOLVE = 'resolve'¶
Config.imports and Config.deny_imports decide which modules stubpy may import;
Config.import_policy returns them as an ImportPolicy.
- class ImportPolicy(imports: str | tuple[str, ...] = 'all', deny: tuple[str, ...] = ())[source]¶
Bases:
objectimports (
"all","none","stdlib"or allowed patterns plus the stdlib) minus deny.Examples
>>> policy = ImportPolicy(("mypkg",), ("mypkg.gui.*",)) >>> policy.allows("json"), policy.allows("mypkg.core"), policy.allows("mypkg.gui.qt"), policy.allows("numpy") (True, True, False, False)
Config.docstrings holds the stubs that stubpy docstrings acts on when it gets no
arguments. A mapping coerces to this class.
- class DocstringTargets(packages: tuple[str, ...] = (), import_root: str | None = None, overrides: tuple[tuple[str, str], ...] = ())[source]¶
Bases:
objectThe stubs
stubpy docstringsacts on when it gets no STUB or-m MODULE.- Variables:
packages (tuple of str) – Folders searched for
*.pyxfiles and compiled modules that have a.pyiof the same stem next to them.import_root (str or None) – The folder module names are relative to (
"src"for a src layout);Nonefinds it by walking up__init__.pyfolders.overrides (tuple of (str, str)) –
(module, stub path)pairs, from a mapping, for stubs of another name or place; an empty path drops a discovered module.
Examples
>>> DocstringTargets.coerce({"packages": ["mypkg"]}).packages ('mypkg',)
- classmethod coerce(value: Any) DocstringTargets[source]¶
Return value (an instance or a
[tool.stubpy.docstrings]mapping) validated.
- resolved(base: str) DocstringTargets[source]¶
Return a copy with relative paths joined onto base (the folder of the config file).