annotation_to_str

annotation_to_str(annotation: Any, ctx: StubContext) str[source]

Convert any annotation object to a valid .pyi string.

Resolution order:

  1. inspect.Parameter.empty or inspect.Signature.empty""

  2. Alias-registry lookup via lookup_alias() — if the annotation matches a registered alias it is returned as-is (e.g. "types.Length") and the alias module is marked as used.

  3. Registered dispatch handlers, tried in order.

  4. Fallback: str(annotation).replace("typing.", "").

This function is recursive — generic argument lists are processed by calling it on each __args__ element.

Parameters:
  • annotation (Any) – Any live Python annotation object. Accepted values include plain types (int, str), PEP 604 unions (str | None), subscripted typing generics (Optional[int]), string forward references ("Element"), typing.ForwardRef objects, NoneType, and inspect.Parameter.empty.

  • ctx (StubContext) – The current StubContext. Used for alias lookup and to track which type-module imports are needed.

Returns:

str – A stub-safe string representation, or "" for empty sentinels.

See also

format_param

Formats a full parameter including name and default.

stubpy.context.StubContext.lookup_alias

Alias resolution logic.

Examples

>>> from stubpy.context import StubContext
>>> from stubpy.annotations import annotation_to_str
>>> from typing import Optional, List
>>> ctx = StubContext()
>>> annotation_to_str(int, ctx)
'int'
>>> annotation_to_str(str | None, ctx)
'Optional[str]'
>>> annotation_to_str(List[int], ctx)
'List[int]'
>>> annotation_to_str("Element", ctx)
'Element'
>>> annotation_to_str(type(None), ctx)
'None'

See also

Public API reference — overview of all public names.