On this page
  1. annotationlib
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Handling Forward References Safely (Format.FORWARDREF)
  7. Gotchas & Boundaries
  8. Common Functions
  9. Classes & Objects

annotationlib

Prev: abc | Up: stdlib_module | Next: antigravity
Rel: typing, pydoc, pydoc_data, doctest, unittest
Ref: docs.python.org — annotationlib
Tags: #public #python3 #stdlib


Import

import annotationlib

Overview

Python 3.14+ deferred annotation introspection (get_annotations, Format, ForwardRef, call_annotate_function) implementing PEP 649 / PEP 749. Essential for runtime validators, CLI generators, and ORM/dataclass frameworks that inspect type hints safely even when forward references are unresolved.

Quick Start

import annotationlib
from annotationlib import Format

def greet(name: str, count: int = 1) -> str:
    return name * count

val_ann = annotationlib.get_annotations(greet, format=Format.VALUE)
str_ann = annotationlib.get_annotations(greet, format=Format.STRING)
assert val_ann["name"] is str
assert str_ann["count"] == "int"

Implementation Walkthrough

1. Handling Forward References Safely (Format.FORWARDREF)

Under PEP 649, annotations are evaluated lazily on access. Requesting Format.FORWARDREF returns real objects where resolved and ForwardRef placeholders for undefined names instead of raising NameError:

import annotationlib
from annotationlib import Format

class Node:
    def next_node(self) -> "MissingType": ...

hints = annotationlib.get_annotations(Node.next_node, format=Format.FORWARDREF)
assert isinstance(hints["return"], (str, annotationlib.ForwardRef))

Gotchas & Boundaries

Common Functions

Classes & Objects

Linked from

Related notes