Add `annotationlib`, `get_type_hints` formats and PEP 563 handling

Merged
SA
1mo ago
+3400-351
  • from __future__ import annotations is recorded on the functions and classes that follow it, so get_type_hints() evaluates their annotations as PEP 563 strings in the given namespaces only.
  • typing.get_type_hints(format=) accepts VALUE, FORWARDREF and STRING. FORWARDREF loads an unresolved name as a ForwardRef stringifier that composes source text for every operation, as CPython's annotationlib does; STRING returns the stored text.
  • New annotationlib module: Format, ForwardRef (a native type, also typing.ForwardRef) and get_annotations(), with a narrowed type stub.
  • Hint snippets always resolve names at run time, so a cached snippet sees a builtin rebound after it was compiled; every annotation evaluates before any forward reference resolves.
  • Divergences in limitations/typing.md and limitations/annotationlib.md.

Claude-Session: https://claude.ai/code/session_018zfZ5wGot8GsLjx4cowPZx


Summary by cubic

Adds PEP 563 handling, a new annotationlib module, and format support for typing.get_type_hints(). from __future__ import annotations was previously accepted as a no-op; the flag is now stamped on each compiled Code, inherited by exec()/eval() calls (including a global bound to exec), and persisted across REPL feeds, so get_type_hints() evaluates those annotations as PEP 563 strings in the given namespaces only. A __future__ import after any other statement is now a SyntaxError, as in CPython.

typing.get_type_hints(format=) now accepts VALUE, FORWARDREF, and STRING. FORWARDREF returns an unresolved name as a ForwardRef stringifier that composes source text for every operation, matching CPython's annotationlib; STRING returns the stored text. The new annotationlib module provides Format, ForwardRef (also typing.ForwardRef), and get_annotations(), with a narrowed type stub.

Behavior changes

  • Compiled class bodies end with a hidden type.__build_class__ builtin that carries the PEP 563 flag; a plain type() call doesn't, and its hand-built namespaces treat string annotations as forward references.
  • Only references a FORWARDREF evaluation created compose source text; a ForwardRef built by code an annotation calls behaves normally.
  • Hint snippets resolve names at run time, so a cached snippet sees a builtin rebound after it was compiled; every annotation evaluates before any forward reference resolves.
  • ForwardRef.evaluate() requires dict or None globals/locals for VALUE and FORWARDREF; STRING returns the text before the namespaces are validated. It honors module= by selecting that module's namespace (file module, bundled module, or __main__), and resolves a composed reference against the globals it was built in.

Documentation

  • Divergences recorded in limitations/typing.md and limitations/annotationlib.md.