stubpy.extend

The advanced namespace. See Extending stubpy for worked examples. Diagnostic and Level are re-exported here unchanged; they are documented in Results and diagnostics.

Annotation handlers

register_annotation_handler(predicate: Callable[[Any], bool], *, first: bool = False) → Callable[[Callable[[Any, StubContext], str]], Callable[[Any, StubContext], str]][source]

Register a custom annotation-to-string handler.

A handler turns a live annotation object into stub text. By default it runs after every built-in handler, so it only sees annotations none of them matched; first=True puts it ahead of all registered handlers.

Parameters:
  • predicate (callable) – predicate(annotation) -> bool; True for the annotations the handler renders.

  • first (bool, default False) – Try this handler before every other one.

Returns:

callable – A decorator that registers handler(annotation, ctx) -> str and returns it unchanged.

Examples

from stubpy.extend import annotation_to_str, register_annotation_handler

@register_annotation_handler(lambda a: isinstance(a, Validated))
def _validated(annotation, ctx):
    return f"Validated[{annotation_to_str(annotation.inner_type, ctx)}]"
annotation_to_str(annotation: Any, ctx: StubContext) → str[source]

Render a live annotation object as stub text.

Empty sentinels give ""; a registered alias wins; then the first matching handler; otherwise str(annotation) without typing., or "" when that is not an expression (an object’s <...> repr).

Examples

>>> from typing import List
>>> annotation_to_str(List[int], StubContext())
'list[int]'

Forwarding resolvers and stub hooks

register_forward_resolver(fn: Callable[[str, dict[str, Any]], Any]) → Callable[[str, dict[str, Any]], Any][source]

Register fn to name the target of a **kwargs / *args forward, such as one stubpy cannot find.

fn is called as fn(name, namespace) with the call-site text ("draw", "self.backend.draw") and the module’s globals, and returns the callable or class the call forwards to, or None to leave it to stubpy. Resolvers are asked before stubpy’s own lookup, in registration order; the first non-None result wins. They need the module’s live objects, so they are not used with imports="none". Usable as a decorator.

Parameters:

fn (callable) – (name: str, namespace: dict[str, Any]) -> object | None.

Returns:

callable – fn, unchanged.

See also

register_stub_hook

Change the finished stub text.

Examples

>>> @register_forward_resolver
... def backend(name: str, namespace: dict) -> object | None:
...     return namespace.get("Renderer").draw if name == "self.backend.draw" else None
>>> FORWARD_RESOLVERS.remove(backend)
register_stub_hook(fn: Callable[[str, StubContext], str]) → Callable[[str, StubContext], str][source]

Register fn to change each module’s finished stub text before it is written or compared.

fn is called as fn(text, ctx); ctx.module_name names the module. Hooks run in registration order, each on the previous one’s result. Usable as a decorator.

Parameters:

fn (callable) – (text: str, ctx: StubContext) -> str.

Returns:

callable – fn, unchanged.

See also

register_forward_resolver

Name forwarding targets stubpy cannot find.

Examples

>>> @register_stub_hook
... def banner(text: str, ctx: StubContext) -> str:
...     return "# Generated; do not edit.\n" + text
>>> STUB_HOOKS.remove(banner)

Symbol table

ast_harvest(source: str, tree: Module | None = None, version_branches: bool = False) → ASTSymbols[source]

Parse source and return its structural metadata without executing it.

Parameters:
  • source (str) – Python source text.

  • tree (ast.Module, optional) – The already parsed source, to avoid parsing it twice. Defaults to None.

  • version_branches (bool, optional) – Harvest every branch of sys.version_info / sys.platform tests, tagging definitions with their branch; by default only the branch this interpreter takes. Defaults to False.

Returns:

ASTSymbols – Harvested classes, functions, variables, type declarations and __all__. Empty but valid on SyntaxError.

See also

ASTHarvester

The visitor behind this function.

Examples

>>> syms = ast_harvest("class Foo(Bar): pass")
>>> syms.classes[0].name, syms.classes[0].bases
('Foo', ['Bar'])
>>> ast_harvest("X = TypeVar('X')").typevar_decls[0].kind
'TypeVar'
build_symbol_table(module: ModuleType | None, module_name: str, ast_symbols: ASTSymbols, all_exports: set[str] | None = None, include_private: bool = False, diagnostics: DiagnosticCollector | None = None) → SymbolTable[source]

Build a SymbolTable from AST metadata and, when available, the live module.

Symbols are added in this order: type aliases / TypeVars, classes (sorted by source line), functions, overload groups, variables. Classes, aliases and variables that are private or outside __all__ are held back as hidden symbols; the emitter promotes the ones a stub refers to (a TypeVar, a private base class). A name defined more than once (if/else or try/except variants) keeps its first definition. Module dunders such as __version__ and __getattr__ count as public.

Parameters:
  • module (types.ModuleType or None) – The loaded module, or None when the module was not imported (all live_* fields are then None).

  • module_name (str) – Synthetic module name, used to tell local classes from imported ones.

  • ast_symbols (ASTSymbols) – Output of ast_harvest().

  • all_exports (set of str, optional) – When given, public names outside this set are dropped. Defaults to None.

  • include_private (bool, optional) – Keep names starting with _. Defaults to False.

  • diagnostics (DiagnosticCollector, optional) – Receives notes about variables whose type cannot be determined. Defaults to None.

Returns:

SymbolTable – The populated table.

Examples

>>> from stubpy.analysis.harvest import ast_harvest
>>> table = build_symbol_table(None, "mymod", ast_harvest("class A: ...\ndef f(): ...\nX = 1"))
>>> table.all_names()
['A', 'f', 'X']
class SymbolTable[source]

Bases: object

Ordered collection of the symbols of one module.

Keeps definition order and supports lookup by name and iteration by kind.

Examples

>>> tbl = SymbolTable()
>>> tbl.add(ClassSymbol(name="Foo", lineno=1))
>>> tbl.add(FunctionSymbol(name="bar", lineno=10))
>>> len(tbl), "Foo" in tbl, tbl.get("Missing") is None
(2, True, True)
add(symbol: StubSymbol) → None[source]

Append symbol; a later symbol with the same name wins lookups, unless it is dormant and the earlier is not.

Parameters:

symbol (StubSymbol) – The symbol to add.

Examples

>>> tbl = SymbolTable()
>>> tbl.add(ClassSymbol(name="Foo", lineno=1))
>>> tbl.all_names()
['Foo']
discard(name: str) → None[source]

Remove every symbol named name, hidden or not.

Parameters:

name (str) – Name of the symbols to drop.

Examples

>>> tbl = SymbolTable()
>>> tbl.add(ClassSymbol(name="Foo", lineno=1))
>>> tbl.discard("Foo")
>>> len(tbl)
0
add_hidden(symbol: StubSymbol) → None[source]

Keep symbol out of the stub unless promote() brings it in (private or outside __all__).

Parameters:

symbol (StubSymbol) – The symbol to hold back.

See also

promote

Move a hidden symbol into the table.

Examples

>>> tbl = SymbolTable()
>>> tbl.add_hidden(ClassSymbol(name="_Base", lineno=1))
>>> len(tbl), tbl.hidden_names()
(0, {'_Base'})
hidden_names() → set[str][source]

Return the names of the symbols held back from the stub.

Returns:

set of str – Names added with add_hidden() and not yet promoted.

Examples

>>> SymbolTable().hidden_names()
set()
promote(name: str) → list[StubSymbol][source]

Move the hidden symbols named name (one per version branch) into the table and return them.

Parameters:

name (str) – Name of the hidden symbols.

Returns:

list of StubSymbol – The promoted symbols; empty when none are hidden under name.

Examples

>>> tbl = SymbolTable()
>>> tbl.add_hidden(ClassSymbol(name="_Base", lineno=1))
>>> [s.name for s in tbl.promote("_Base")], len(tbl)
(['_Base'], 1)
function_infos() → dict[source]

Map each function name to its AST FunctionInfo, computed once per table state.

Returns:

dict – Function name to FunctionInfo, for the functions that have AST metadata.

Examples

>>> tbl = SymbolTable()
>>> tbl.add(FunctionSymbol(name="bar", lineno=1))
>>> tbl.function_infos()
{}
get(name: str, hidden: bool = False) → StubSymbol | None[source]

Return the symbol named name, or None.

Parameters:
  • name (str) – The symbol name.

  • hidden (bool, optional) – Also look among the hidden symbols. Defaults to False.

Returns:

StubSymbol or None – The visible symbol, else a hidden one when hidden is set.

Examples

>>> tbl = SymbolTable()
>>> tbl.add(ClassSymbol(name="Foo", lineno=1))
>>> tbl.get("Foo").name, tbl.get("Bar")
('Foo', None)
get_class(name: str) → ClassSymbol | None[source]

Return the ClassSymbol named name, hidden or not, or None.

Parameters:

name (str) – The class name.

Returns:

ClassSymbol or None – The class symbol, or None when name is missing or not a class.

Examples

>>> tbl = SymbolTable()
>>> tbl.add_hidden(ClassSymbol(name="_Base", lineno=1))
>>> tbl.get_class("_Base").name
'_Base'
get_function(name: str) → FunctionSymbol | None[source]

Return the FunctionSymbol named name, or None.

Parameters:

name (str) – The function name.

Returns:

FunctionSymbol or None – The function symbol, or None when name is missing or not a function.

Examples

>>> tbl = SymbolTable()
>>> tbl.add(FunctionSymbol(name="bar", lineno=1))
>>> tbl.get_function("bar").name, tbl.get_function("Foo")
('bar', None)
by_kind(kind: SymbolKind) → Iterator[StubSymbol][source]

Yield the symbols of kind in definition order.

Parameters:

kind (SymbolKind) – The category to select.

Yields:

StubSymbol – Each matching symbol.

Examples

>>> tbl = SymbolTable()
>>> tbl.add(ClassSymbol(name="Foo", lineno=1))
>>> [s.name for s in tbl.by_kind(SymbolKind.CLASS)]
['Foo']
classes() → Iterator[ClassSymbol][source]

Yield the class symbols in definition order.

Yields:

ClassSymbol – Each class symbol.

Examples

>>> tbl = SymbolTable()
>>> tbl.add(ClassSymbol(name="Foo", lineno=1))
>>> [s.name for s in tbl.classes()]
['Foo']
functions() → Iterator[FunctionSymbol][source]

Yield the function symbols in definition order.

Yields:

FunctionSymbol – Each function symbol.

Examples

>>> tbl = SymbolTable()
>>> tbl.add(FunctionSymbol(name="bar", lineno=1))
>>> [s.name for s in tbl.functions()]
['bar']
variables() → Iterator[VariableSymbol][source]

Yield the variable symbols in definition order.

Yields:

VariableSymbol – Each variable symbol.

Examples

>>> tbl = SymbolTable()
>>> tbl.add(VariableSymbol(name="MAX", lineno=1))
>>> [s.name for s in tbl.variables()]
['MAX']
aliases() → Iterator[AliasSymbol][source]

Yield the alias symbols in definition order.

Yields:

AliasSymbol – Each alias symbol.

Examples

>>> tbl = SymbolTable()
>>> tbl.add(AliasSymbol(name="T", lineno=1))
>>> [s.name for s in tbl.aliases()]
['T']
overload_groups() → Iterator[OverloadGroup][source]

Yield the overload groups in definition order.

Yields:

OverloadGroup – Each overload group.

Examples

>>> tbl = SymbolTable()
>>> tbl.add(OverloadGroup(name="parse", lineno=1))
>>> [s.name for s in tbl.overload_groups()]
['parse']
all_names() → list[str][source]

Return all symbol names in definition order.

Returns:

list of str – The names of the visible symbols, in the order they were added.

Examples

>>> tbl = SymbolTable()
>>> tbl.add(ClassSymbol(name="Foo", lineno=1))
>>> tbl.all_names()
['Foo']
sorted_by_line() → list[StubSymbol][source]

Return all symbols sorted by source line.

Returns:

list of StubSymbol – The visible symbols, lowest line first.

Examples

>>> tbl = SymbolTable()
>>> tbl.add(FunctionSymbol(name="bar", lineno=10))
>>> tbl.add(ClassSymbol(name="Foo", lineno=1))
>>> [s.name for s in tbl.sorted_by_line()]
['Foo', 'bar']
class ASTSymbols(classes: list[ClassInfo] = <factory>, functions: list[FunctionInfo] = <factory>, variables: list[VariableInfo] = <factory>, typevar_decls: list[TypeVarInfo] = <factory>, all_exports: list[str] | None = None, all_spliced: list[str] = <factory>, all_dynamic: bool = False, imports: list[ImportInfo] = <factory>, skip_file: bool = False)[source]

Bases: object

Everything ast_harvest() collects from one source file.

Every definition carries branch: the version blocks (VersionBlock) it sits in when they are harvested with version_branches=True, else ().

Variables:
  • classes (list of ClassInfo) – Top-level classes, in source order.

  • functions (list of FunctionInfo) – Top-level functions, in source order.

  • variables (list of VariableInfo) – Top-level variable assignments.

  • typevar_decls (list of TypeVarInfo) – TypeVar / ParamSpec / TypeVarTuple / TypeAlias / NewType declarations.

  • all_exports (list of str or None) – String entries of __all__, or None when absent or not a literal list.

  • all_spliced (list of str) – Names spliced into __all__ with *name (usually another module’s __all__ imported under that name); all_exports is then incomplete on its own. mod.__all__ of an imported module is recorded as "mod.__all__".

  • all_dynamic (bool) – True when __all__ is changed in a way the source cannot be read for (__all__ += helper(), __all__.remove(...)); only the runtime __all__ is then trustworthy.

  • imports (list of ImportInfo) – Top-level imports, in source order.

  • skip_file (bool) – True when the file starts with a # stubpy: ignore directive.

Examples

>>> symbols = ASTSymbols()
>>> symbols.classes, symbols.all_exports, symbols.skip_file
([], None, False)
classes: list[ClassInfo]
functions: list[FunctionInfo]
variables: list[VariableInfo]
typevar_decls: list[TypeVarInfo]
all_exports: list[str] | None = None
all_spliced: list[str]
all_dynamic: bool = False
imports: list[ImportInfo]
skip_file: bool = False
class ClassSymbol(name: str, lineno: int, live_type: type | None = None, ast_info: ClassInfo | None = None)[source]

Bases: StubSymbol

A class definition.

Parameters:
  • name (str) – Class name.

  • lineno (int) – Source line of the definition.

  • live_type (type, optional) – The runtime class; None when the module was not imported. Defaults to None.

  • ast_info (ClassInfo, optional) – Metadata from the AST pre-pass. Defaults to None.

Examples

>>> ClassSymbol(name="Widget", lineno=5).kind
<SymbolKind.CLASS: 'class'>
live_type: type | None = None
ast_info: ClassInfo | None = None
class FunctionSymbol(name: str, lineno: int, live_func: Any | None = None, ast_info: FunctionInfo | None = None, is_async: bool = False)[source]

Bases: StubSymbol

A top-level function definition.

Parameters:
  • name (str) – Function name.

  • lineno (int) – Source line of the definition.

  • live_func (callable, optional) – The runtime function; None when the module was not imported. Defaults to None.

  • ast_info (FunctionInfo, optional) – Metadata from the AST pre-pass. Defaults to None.

  • is_async (bool, optional) – Taken from ast_info when given. Defaults to False.

Examples

>>> FunctionSymbol(name="greet", lineno=3, is_async=True).is_async
True
live_func: Any | None = None
ast_info: FunctionInfo | None = None
is_async: bool = False
class VariableSymbol(name: str, lineno: int, live_value: Any = None, annotation_str: str | None = None, inferred_type_str: str | None = None, ast_info: VariableInfo | None = None)[source]

Bases: StubSymbol

A module-level variable.

Parameters:
  • name (str) – Variable name.

  • lineno (int) – Source line of the assignment.

  • live_value (Any, optional) – The runtime value; None when the module was not imported. Defaults to None.

  • annotation_str (str, optional) – Annotation from the source. Defaults to None.

  • inferred_type_str (str, optional) – Type inferred from the value when there is no annotation. Defaults to None.

  • ast_info (VariableInfo, optional) – Metadata from the AST pre-pass. Defaults to None.

Examples

>>> VariableSymbol(name="MAX", lineno=1, annotation_str="int").effective_type_str
'int'
live_value: Any = None
annotation_str: str | None = None
inferred_type_str: str | None = None
ast_info: VariableInfo | None = None
property effective_type_str: str | None

The annotation if present, else the inferred type.

Returns:

str or None – The type text, or None when neither is known.

Examples

>>> VariableSymbol(name="N", lineno=1, inferred_type_str="int").effective_type_str
'int'
class AliasSymbol(name: str, lineno: int, ast_info: TypeVarInfo | None = None, live_obj: Any = None)[source]

Bases: StubSymbol

A TypeAlias, TypeVar, ParamSpec, TypeVarTuple or NewType declaration.

Parameters:
  • name (str) – Declared name.

  • lineno (int) – Source line of the declaration.

  • ast_info (TypeVarInfo, optional) – Metadata from the AST pre-pass. Defaults to None.

  • live_obj (Any, optional) – The runtime object, if available. Defaults to None.

Examples

>>> AliasSymbol(name="T", lineno=2).kind
<SymbolKind.ALIAS: 'alias'>
ast_info: TypeVarInfo | None = None
live_obj: Any = None
class OverloadGroup(name: str, lineno: int, variants: list[FunctionSymbol] | None = None, live_func: Any | None = None)[source]

Bases: StubSymbol

The @overload variants sharing one function name.

Parameters:
  • name (str) – The overloaded function’s name.

  • lineno (int) – Source line of the first variant.

  • variants (list of FunctionSymbol, optional) – One entry per @overload definition, in source order. Defaults to an empty list.

  • live_func (callable, optional) – The runtime implementation. Defaults to None.

Examples

>>> OverloadGroup(name="parse", lineno=7).variants
[]
variants: list[FunctionSymbol]
live_func: Any | None = None
class SymbolKind(*values)[source]

Bases: Enum

Category of a stub symbol.

Examples

>>> SymbolKind("class") is SymbolKind.CLASS
True
CLASS = 'class'
FUNCTION = 'function'
VARIABLE = 'variable'
ALIAS = 'alias'
OVERLOAD = 'overload'

Run context and diagnostics

class StubContext(alias_registry: list[AliasEntry] = <factory>, type_module_imports: dict[str, str]=<factory>, used_type_imports: dict[str, str]=<factory>, config: Config = <factory>, diagnostics: DiagnosticCollector = <factory>, symbol_table: Any | None = None, all_exports: set[str] | None = None, all_order: list[str] = <factory>, star_exports: dict[str, list[str]]=<factory>, star_public: dict[str, list[str]]=<factory>, module_namespace: dict[str, ~typing.Any]=<factory>, module_name: str = '', import_map: dict[str, str]=<factory>, extra_imports: dict[str, str]=<factory>, module_loader: Any | None = None, branch_imports: list[Any] = <factory>, source_index: Any | None = None, source_module: Any | None = None, requested_names: set[str] = <factory>, submodule: str = '', submodules: list[str] = <factory>, _alias_index: dict[~typing.Any, str] | None=None, _alias_index_size: int = -1)[source]

Bases: object

Mutable state for stubbing one module.

Every emitter and annotation handler receives it; extensions read ctx.config and record issues in ctx.diagnostics. Every field is optional and starts empty, so StubContext() is valid.

Parameters:
  • alias_registry (list of AliasEntry) – Type aliases registered from imported sub-modules.

  • type_module_imports (dict) – Import statements for alias sub-modules, keyed by local name.

  • used_type_imports (dict) – Subset of type_module_imports actually referenced in the stub.

  • config (Config) – Per-run options.

  • diagnostics (DiagnosticCollector) – Warnings and errors from the pipeline.

  • symbol_table (SymbolTable or None) – Populated by the symbol-table stage.

  • all_exports (set of str or None) – Contents of the target module’s __all__, if any.

  • all_order (list of str) – The same names in their __all__ order, for the stub’s own __all__.

  • star_exports (dict) – For each from m import * of the module, the names it binds when m declares __all__; the stub re-exports them one by one.

  • star_public (dict) – {module: public names} of imported star targets without __all__; a stub expands such a star only when it redefines one of them (a star then a redefinition is an error for type checkers).

  • module_namespace (dict) – __dict__ of the loaded module, used to look up forwarding targets. Empty when the module was not imported.

  • module_name (str) – __name__ of the target module (synthetic for loose scripts).

  • import_map (dict) – {local_name: import_statement} for the imports in the source.

  • extra_imports (dict) – Imports the emitters needed beyond the source’s annotations, keyed by local name (for example the class of an enum default).

  • module_loader (ModuleLoader or None) – Loader shared by a package run; None makes each run use its own.

  • branch_imports (list of ImportInfo) – Imports inside version branches; the body writes the ones it needs inside their branch instead of the header.

  • source_index (SourceIndex or None) – Harvested sources shared by a run, for back-tracing without imports.

  • source_module (SourceModule or None) – The module being stubbed in that index; variadics are resolved from it when the module was not imported (module_namespace is empty).

  • requested_names (set of str) – Names other modules of the run import from this one; they are kept in the stub even when private or outside __all__.

  • submodule (str) – For a compiled extension, the dotted path of the attribute submodule to stub ("fft" for pkg.fft); "" for the extension itself.

  • submodules (list of str) – The attribute submodules of the compiled module just stubbed, by attribute name.

Examples

>>> ctx = StubContext()
>>> ctx.diagnostics.summary()
'0 errors, 0 warnings, 0 infos'
>>> ctx.config.may_import
True
alias_registry: list[AliasEntry]
type_module_imports: dict[str, str]
used_type_imports: dict[str, str]
config: Config
diagnostics: DiagnosticCollector
symbol_table: Any | None = None
all_exports: set[str] | None = None
all_order: list[str]
star_exports: dict[str, list[str]]
star_public: dict[str, list[str]]
module_namespace: dict[str, Any]
module_name: str = ''
import_map: dict[str, str]
extra_imports: dict[str, str]
module_loader: Any | None = None
branch_imports: list[Any]
source_index: Any | None = None
source_module: Any | None = None
requested_names: set[str]
submodule: str = ''
submodules: list[str]
lookup_alias(annotation: Any) → str | None[source]

Return the alias string registered for annotation, or None.

A hit also marks the alias module’s import as used.

Parameters:

annotation (object) – The annotation to look up; unhashable ones are compared by equality.

Returns:

str or None – The registered alias text, or None when there is none.

Examples

>>> ctx = StubContext()
>>> ctx.alias_registry.append(AliasEntry(str | int, "types.T"))
>>> ctx.type_module_imports["types"] = "from pkg import types"
>>> ctx.lookup_alias(str | int)
'types.T'
class AliasEntry(annotation: Any, alias_str: str)[source]

Bases: NamedTuple

A live annotation object paired with the alias string emitted for it.

Parameters:
  • annotation (object) – The annotation object as seen at runtime.

  • alias_str (str) – The text written in the stub, e.g. "types.Length".

Examples

>>> entry = AliasEntry(annotation=str | float | int, alias_str="types.Length")
>>> entry.alias_str
'types.Length'
annotation: Any

Alias for field number 0

alias_str: str

Alias for field number 1

class DiagnosticCollector(_items: list[Diagnostic] = <factory>)[source]

Bases: object

Ordered accumulator of Diagnostic records for one run.

Every StubContext owns one, so pipeline stages can record issues without raising.

Examples

>>> collector = DiagnosticCollector()
>>> collector.warning(Stage.EMIT, "Foo.bar", "No return annotation")
>>> collector.has_warnings(), len(collector)
(True, 1)
add(level: Level, stage: Stage, symbol: str, message: str) → None[source]

Append a diagnostic record.

Parameters:
  • level (Level) – Severity.

  • stage (Stage) – Pipeline stage that raised it.

  • symbol (str) – Name of the symbol being processed.

  • message (str) – Human-readable description.

Examples

>>> c = DiagnosticCollector()
>>> c.add(Level.INFO, Stage.LOAD, "mod", "loaded")
>>> len(c)
1
info(stage: Stage, symbol: str, message: str) → None[source]

Record an INFO diagnostic.

Parameters:
  • stage (Stage) – Pipeline stage that raised it.

  • symbol (str) – Name of the symbol being processed.

  • message (str) – Human-readable description.

Examples

>>> c = DiagnosticCollector()
>>> c.info(Stage.LOAD, "mod", "loaded")
>>> c.has_info()
True
warning(stage: Stage, symbol: str, message: str) → None[source]

Record a WARNING diagnostic.

Parameters:
  • stage (Stage) – Pipeline stage that raised it.

  • symbol (str) – Name of the symbol being processed.

  • message (str) – Human-readable description.

Examples

>>> c = DiagnosticCollector()
>>> c.warning(Stage.RESOLVE, "Child.__init__", "unresolved **kwargs")
>>> c.has_warnings()
True
error(stage: Stage, symbol: str, message: str) → None[source]

Record an ERROR diagnostic.

Parameters:
  • stage (Stage) – Pipeline stage that raised it.

  • symbol (str) – Name of the symbol being processed.

  • message (str) – Human-readable description.

Examples

>>> c = DiagnosticCollector()
>>> c.error(Stage.LOAD, "mod", "cannot import")
>>> c.has_errors()
True
property all: list[Diagnostic]

All recorded diagnostics, in order.

property info_items: list[Diagnostic]

All INFO diagnostics.

has_info() → bool[source]

Return True if any INFO diagnostic was recorded.

Returns:

bool – Whether at least one INFO diagnostic exists.

Examples

>>> DiagnosticCollector().has_info()
False
property warnings: list[Diagnostic]

All WARNING diagnostics.

property errors: list[Diagnostic]

All ERROR diagnostics.

property infos: list[Diagnostic]

All INFO diagnostics.

has_errors() → bool[source]

Return True if any ERROR diagnostic was recorded.

Returns:

bool – Whether at least one ERROR diagnostic exists.

Examples

>>> DiagnosticCollector().has_errors()
False
has_warnings() → bool[source]

Return True if any WARNING diagnostic was recorded.

Returns:

bool – Whether at least one WARNING diagnostic exists.

Examples

>>> DiagnosticCollector().has_warnings()
False
by_stage(stage: Stage) → list[Diagnostic][source]

Return all diagnostics from stage.

Parameters:

stage (Stage) – The stage to select.

Returns:

list of Diagnostic – The matching diagnostics, in order.

Examples

>>> c = DiagnosticCollector()
>>> c.warning(Stage.EMIT, "f", "no return annotation")
>>> len(c.by_stage(Stage.EMIT)), len(c.by_stage(Stage.LOAD))
(1, 0)
by_symbol(symbol: str) → list[Diagnostic][source]

Return all diagnostics recorded for symbol.

Parameters:

symbol (str) – The symbol name, exactly as recorded.

Returns:

list of Diagnostic – The matching diagnostics, in order.

Examples

>>> c = DiagnosticCollector()
>>> c.warning(Stage.EMIT, "f", "no return annotation")
>>> [d.message for d in c.by_symbol("f")]
['no return annotation']
summary() → str[source]

Return a one-line count summary, e.g. '0 errors, 0 warnings, 0 infos'.

Returns:

str – The number of errors, warnings and infos.

Examples

>>> c = DiagnosticCollector()
>>> c.error(Stage.LOAD, "mod", "cannot import")
>>> c.summary()
'1 errors, 0 warnings, 0 infos'
format_all() → str[source]

Return all diagnostics joined by newlines.

Returns:

str – One str(diagnostic) line per record; empty when there are none.

Examples

>>> c = DiagnosticCollector()
>>> c.info(Stage.LOAD, "mod", "loaded")
>>> print(c.format_all())
[INFO] (load) mod: loaded
clear() → None[source]

Remove all recorded diagnostics.

Examples

>>> c = DiagnosticCollector()
>>> c.info(Stage.LOAD, "mod", "loaded")
>>> c.clear()
>>> len(c)
0
class Stage(*values)[source]

Bases: Enum

Pipeline stage that produced a Diagnostic.

Variables:

TYPECHECK (LOAD, AST_PASS, SYMBOL_TABLE, ALIAS, RESOLVE, EMIT, IMPORT, GENERATOR,) – Loading the module, the AST pre-pass, building the symbol table, alias detection, **kwargs / *args resolution, stub emission, import assembly, run-level steps such as writing and merging, and type-checking the written stubs (typecheck).

Examples

>>> Stage.RESOLVE.value
'resolve'
LOAD = 'load'
AST_PASS = 'ast_pass'
SYMBOL_TABLE = 'symbol_table'
ALIAS = 'alias'
RESOLVE = 'resolve'
EMIT = 'emit'
IMPORT = 'import'
GENERATOR = 'generator'
TYPECHECK = 'typecheck'