register_annotation_handler

register_annotation_handler(predicate: Callable[[Any], bool]) Callable[source]

Register a custom annotation-to-string handler.

Teaches stubpy how to render annotation types it does not recognise — for example Pydantic Annotated wrappers, custom metaclasses, or future PEP annotation forms.

Handlers are appended after all built-in handlers and therefore only run for annotations that no built-in handler matches.

Parameters:

predicate (callable) – A single-argument callable returning True when your handler should process the given annotation object.

Returns:

callable – The decorated handler function, unmodified.

Examples

Render a custom Validated[T] wrapper in stubs:

from stubpy.annotations import register_annotation_handler, annotation_to_str
from mylib import Validated

@register_annotation_handler(lambda a: isinstance(a, Validated))
def _handle_validated(annotation, ctx):
    inner = annotation_to_str(annotation.inner_type, ctx)
    return f"Validated[{inner}]"

To insert before built-in handlers:

from stubpy.annotations import _ANN_HANDLERS
_ANN_HANDLERS.insert(0, (my_predicate, my_handler))

See also

stubpy.annotations._ANN_HANDLERS

The underlying dispatch table.

See also

Public API reference — overview of all public names.