Inspect Annotations without Evaluating Strings
Core idea
In Python 3.13, inspect.get_annotations returns a fresh dictionary. By default it leaves string annotations unchanged; eval_str=True evaluates strings in the relevant namespace. Annotation representations depend on definition style and Python version, and evaluation can execute code. Inspect trusted objects and keep evaluation off unless needed.
from inspect import get_annotationsdef parse(x: 'int') -> str: return str(x)a = get_annotations(parse)print(a['x'] == 'int', a['return'] is str)An explicit quoted annotation remains text; the other is a type object.
Evaluate a trusted name
from inspect import get_annotationsdef parse(x: 'int'): return xa = get_annotations(parse, eval_str=True)print(a['x'] is int)a.clear()print('x' in get_annotations(parse))The known string resolves to int. Clearing the returned dictionary does not remove original annotations.
Common mistake
Never enable eval_str for arbitrary supplied annotation text. Python 3.14 changes annotation evaluation semantics; this lesson targets 3.13, not a universal safety guarantee.
Practice
Compare an explicit string and a type object using get_annotations; explain when resolving the string is necessary.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Inspect annotations
Check your understanding of inspect annotations.
What is printed?
from inspect import get_annotationsdef f(x: 'str'): passprint(type(get_annotations(f)['x']).__name__)What is printed?
from inspect import get_annotationsdef f(): passprint(get_annotations(f))What can eval_str=True do?
Which version is targeted here?