Extending stubpy¶
stubpy.extend is the advanced namespace: annotation handlers, the run context, the
symbol table, harvesting and diagnostics. Its API is less settled than the one in
API Reference.
Custom annotation handlers¶
When an annotation is an object stubpy does not recognise, it is written as <... object at
0x...>. A handler turns it into stub text.
# vlib.py
class Validated:
def __init__(self, inner_type):
self.inner_type = inner_type
# service.py
from vlib import Validated
def clamp(value: Validated(int), lo: Validated(float) = 0.0) -> int: ...
Without a handler, stubpy render service.py writes:
def clamp(value: <vlib.Validated object at 0x000001D36F530690>, lo: <vlib.Validated object at 0x000001D36F530550> = 0.0) -> int: ...
Register one, then render from Python:
import stubpy
from stubpy.extend import annotation_to_str, register_annotation_handler
from vlib import Validated
@register_annotation_handler(lambda a: isinstance(a, Validated))
def _validated(annotation, ctx):
return f"Validated[{annotation_to_str(annotation.inner_type, ctx)}]"
print(stubpy.render("service.py").text)
from vlib import Validated
def clamp(value: Validated[int], lo: Validated[float] = 0.0) -> int: ...
Rules:
predicate(annotation) -> boolselects the annotations;handler(annotation, ctx) -> strreturns the text.A handler runs after the built-in ones and only sees what they did not match.
first=Trueputs it ahead of all of them.Call
annotation_to_str(inner, ctx)to render nested types, so aliases and imports are tracked inctx.The predicate must match the class object stubpy sees. The module you stub is imported by stubpy, so import the annotation class from an importable library module, as above. The handler list is global to the process.
Note
Handlers only apply to live annotation objects, so they take effect when the module is imported (not with --imports none).
Symbol table access¶
ast_harvest reads a source string and build_symbol_table turns it into a
SymbolTable. Pass None as the live module to work from source
alone.
from stubpy.extend import ast_harvest, build_symbol_table
source = open("mro.py").read()
table = build_symbol_table(None, "mro", ast_harvest(source))
print(table.all_names()) # ['Element', 'Styled', 'Circle']
styled = table.get_class("Styled")
print(styled.ast_info.bases) # ['Element']
The table offers get, get_class, get_function, classes(), functions(),
variables(), aliases(), overload_groups(), by_kind(kind) and sorted_by_line().
Its symbols are ClassSymbol, FunctionSymbol,
VariableSymbol, AliasSymbol and
OverloadGroup.
Forwarding targets¶
stubpy follows **kwargs and *args into the callable they are passed to by name. When
that callable is chosen at runtime (a plugin, a backend attribute), name it with
register_forward_resolver(). It is called with the call-site text and the
module’s globals and returns the target, or None to leave it to stubpy:
from stubpy.extend import register_forward_resolver
@register_forward_resolver
def backend(name, namespace):
if name == "backend_draw":
return namespace["Renderer"].draw
return None
def plot(**kwargs): return backend_draw(**kwargs) then gets Renderer.draw’s
parameters. Resolvers need the live module, so --imports none does not use them.
Stub text hooks¶
register_stub_hook() changes each finished stub before it is written or
compared, for example to add a header:
from stubpy.extend import register_stub_hook
@register_stub_hook
def header(text, ctx):
return f"# Stubs for {ctx.module_name}; generated by stubpy.\n" + text
Hooks run in registration order, each on the previous one’s result. Register resolvers and hooks
before calling generate(); the command line does not load them.
Diagnostics and context¶
StubContext carries the Config, the diagnostics
collector and the import bookkeeping for one module. Handlers receive it as ctx.
Record issues instead of raising:
from stubpy.extend import Stage
ctx.diagnostics.warning(Stage.EMIT, "Validated", "no inner type")
Every public name of the namespace is listed in stubpy.extend.