annotation_to_str¶
- annotation_to_str(annotation: Any, ctx: StubContext) str[source]¶
Convert any annotation object to a valid
.pyistring.Resolution order:
inspect.Parameter.emptyorinspect.Signature.empty→""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.Registered dispatch handlers, tried in order.
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.ForwardRefobjects,NoneType, andinspect.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_paramFormats a full parameter including name and default.
stubpy.context.StubContext.lookup_aliasAlias 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.