PEP 649 `__annotate__`

Merged
SA
1mo ago
+2983-757

Summary by cubic

Implements PEP 649 lazy annotations, replacing stringized annotation storage with compiled __annotate__(format) functions evaluated on access, reported as __annotate__ in tracebacks whatever a class body binds them as, matching CPython 3.14. f.__annotations__/__annotate__ recompute per access; a class's annotations dict is cached on first read.

  • typing generic forms (List[int], ClassVar[int], Callable[[int], str], …) are now subscriptable, building GenericAlias values with CPython's repr and argument checks; Callable[[a, b], r] stores (a, b, r) so get_type_hints resolves forward references inside the list. Non-dunder attribute calls on an alias route to the origin's own lookup, reaching host classes; an unknown attribute raises with the bare name for any special-form origin (ClassVar, Final, Literal, Annotated), and with the collections.abc class name for the ABC-based forms.
  • get_annotations/get_type_hints implement the annotationlib VALUE/FORWARDREF/STRING format fallbacks and strip Annotated unless include_extras; FORWARDREF raises NameError instead of asking the host, and a class is cached only on that success. A non-dict FORWARDREF/STRING result raises CPython's ValueError, while T.__annotations__ keeps the TypeError. get_type_hints treats Literal aliases as leaves, so their string values aren't resolved as forward references.
  • Literal deduplicates and flattens its values by type and hash, comparing and hashing them as a set.
  • typing subscripts and C.__annotations__ preflight their argument and namespace copies (a flattened Annotated as one combined buffer, the fresh annotations dict guarded across its cache insertion), so a large one raises MemoryError instead of hitting the allocator's hard ceiling.
  • getattr()/hasattr() run __annotations__ synchronously, so an annotation's AttributeError yields the default or False; C.__annotations__ = d replaces one the namespace bound.
  • dataclasses reads evaluated annotations at decoration; Field.type holds the value instead of annotation text.
  • Under from __future__ import annotations, annotation dicts hold strings as before, now covered by class__annotations_future.py.