Control Deferred Annotation Evaluation
Core idea
Python 3.14 normally postpones evaluation of annotations until requested. annotationlib.get_annotations provides Format.VALUE for evaluated objects, Format.FORWARDREF for partial resolution with unresolved references represented as ForwardRef objects, and Format.STRING for text approximations. Code using from future import annotations retains string annotation behavior in 3.14. The new API is not a security sandbox: annotation retrieval can execute arbitrary annotation code.
from annotationlib import get_annotations, Formatdef describe(item: Parcel): return itemclass Parcel: passprint(get_annotations(describe, format=Format.VALUE)['item'] is Parcel)The function can be defined before Parcel; the annotation is retrieved after the class exists. Without deferred evaluation or quoting, 3.13 would fail at definition time.
Documented expected output (target runtime not tested locally):
TrueUse an older quoted annotation
from inspect import get_annotationsdef describe(item: 'Parcel'): return itemclass Parcel: passprint(get_annotations(describe)['item'])print(get_annotations(describe, eval_str=True)['item'] is Parcel)In 3.13 this explicitly quoted annotation is a string until trusted evaluation is requested.
Expected output:
ParcelTrueCommon mistake
Do not assume every annotation is a type object or that Format.STRING is safe for inspecting untrusted objects. Avoid eager access in decorators if a forward name is not yet defined; plan when evaluation is permitted.
Practice
On 3.14, retrieve Format.FORWARDREF before defining Parcel, then Format.VALUE afterward. Record the resulting types, and compare the behavior under 3.13 using a quoted annotation.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Deferred annotations and annotationlib
Check your understanding of deferred annotations and annotationlib.
On Python 3.14 (documented expectation; target runtime not tested locally), what is printed?
from annotationlib import get_annotations, Formatdef f(x: Missing): passprint(type(get_annotations(f, format=Format.FORWARDREF)['x']).__name__)What is printed?
from inspect import get_annotationsdef f(x: 'int'): passprint(get_annotations(f)['x'] == 'int')Which format resolves annotations to their actual values?
What must a migration review check?