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: object

Options for one stubpy run.

Every field has a default, so Config() is a valid configuration. Instances are immutable; use replace() to derive a changed copy. Enum fields also accept their string values (union_style="legacy"). Pass one to render(), generate() or check(), or read it from a file with load_config(). Pass one to render(), generate() or check(), or read it from a file with load_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 (pkg or pkg.*, 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 (pkg or pkg.*) 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. 0 disables the limit. Defaults to 300.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 to False.

  • respect_all (bool) – When a module defines __all__, stub only the public names it lists. Defaults to True.

  • include_docstrings (bool) – Use each symbol’s docstring as its stub body instead of .... Defaults to False.

  • 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/end markers and merge it into an existing .pyi, keeping manual edits outside the markers. Defaults to False.

  • resolve_kwargs (bool) – Expand **kwargs into the parameters it is forwarded to. Defaults to True.

  • resolve_args (bool) – Expand *args into the positional parameters it is forwarded to. Defaults to True.

  • 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" copies if 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, .nox and <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 no output; None writes each stub next to its source.

  • prune (bool) – After a run over a folder, remove (generate) or report as stale (check) the .pyi files 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 to False.

  • 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/ (a pyproject.toml and the <pkg>-stubs package with a partial py.typed). Needs an output folder. Defaults to False.

  • 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 stubs stubpy docstrings syncs when given no STUB.

  • array_metadata (bool) – Keep the shape, order and device of nanobind arrays: ndarray[dtype=float32, shape=(*, 3), order='C'] becomes Annotated[NDArray[float32], dict(shape=(None, 3), order='C')], as nanobind’s own stub generator writes it. Defaults to False (a plain NDArray).

  • target_python (str) – Oldest Python ("3.10") the stubs must import on: typing names added later (Self, override, TypeIs, deprecated, …) are imported from typing_extensions. Defaults to "3.10".

Raises:
  • ValueError – If an enum field gets an unknown value.

  • TypeError – If a flag is not a bool or a list field is not a list of strings.

See also

load_config

Read a configuration from stubpy.toml or pyproject.toml.

Config.from_dict

Build 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'
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 = 'modern'
alias_style: AliasStyle = 'compatible'
version_branches: VersionBranches = 'emit'
exclude: tuple[str, ...] = ('.*', '__pycache__', 'build', 'dist', '.venv', 'venv', '*.egg-info', '.git', '.tox', '.nox', '<non-identifier>')
extend_exclude: tuple[str, ...]
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, ...]
modules: tuple[str, ...]
verbose: bool = False
strict: bool = False
array_metadata: bool = False
target_python: str = '3.10'
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_config

Read the mapping from a configuration file.

Examples

>>> Config.from_dict({"include-private": True, "imports": "stdlib"}).imports
'stdlib'
property exclude_patterns: tuple[str, ...]

exclude followed by extend_exclude, as a tuple of patterns.

property may_import: bool

nothing is executed.

Type:

False when imports is "none"

property import_policy: ImportPolicy

The ImportPolicy of imports and deny_imports.

property target_version: tuple[int, int]

target_python as (major, minor).

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_dict

Build 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: _Choice

How unions are written.

Variables:
  • MODERN – PEP 604: int | None. The default.

  • LEGACY – Optional[int] and Union[int, str].

Examples

>>> UnionStyle("legacy") is UnionStyle.LEGACY
True
>>> str(UnionStyle.MODERN)
'modern'
MODERN = 'modern'
LEGACY = 'legacy'
class AliasStyle(*values)[source]

Bases: _Choice

How type aliases are written.

Variables:
  • COMPATIBLE – Name: TypeAlias = rhs. The default.

  • PEP695 – type Name = rhs (readable by Python 3.12+ tools).

  • AUTO – PEP695 when stubpy runs on Python 3.12+, else COMPATIBLE.

Examples

>>> AliasStyle("pep695") is AliasStyle.PEP695
True
>>> str(AliasStyle.COMPATIBLE)
'compatible'
COMPATIBLE = 'compatible'
PEP695 = 'pep695'
AUTO = 'auto'
class VersionBranches(*values)[source]

Bases: _Choice

What happens to if statements testing sys.version_info or sys.platform.

Variables:
  • EMIT – Copy the if / elif / else into 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: object

imports ("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)
imports: str | tuple[str, ...] = 'all'
deny: tuple[str, ...] = ()
property unrestricted: bool

True when every import is allowed, so no guard is needed.

allows(name: str) → bool[source]

True when the policy lets stubpy import module name.

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: object

The stubs stubpy docstrings acts on when it gets no STUB or -m MODULE.

Variables:
  • packages (tuple of str) – Folders searched for *.pyx files and compiled modules that have a .pyi of the same stem next to them.

  • import_root (str or None) – The folder module names are relative to ("src" for a src layout); None finds it by walking up __init__.py folders.

  • 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',)
packages: tuple[str, ...] = ()
import_root: str | None = None
overrides: tuple[tuple[str, str], ...] = ()
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).