Inspect annotations safely when building developer tooling.
What It Does and Why It Matters
Reflection tools may need to examine annotations on functions. annotationlib.get_annotations() provides VALUE, FORWARDREF and STRING representations. VALUE may evaluate annotation expressions, while even STRING and FORWARDREF formats are not guaranteed safe for untrusted code. Never treat annotations from unknown plugins as inert data.
The introspection library was added in Python 3.14; use official guidance and a trusted codebase.
Step-by-Step Example
Start with the complete example below. Read the inputs and predict what the final print statement will show before you run it.
from annotationlib import Format, get_annotations
def report(count: int, title: str) -> bool:
return count > 0 and bool(title)
print(get_annotations(report, format=Format.STRING))
How the Code Works
- The imports make these standard-library tools available: annotationlib.
- The definition of report creates reusable behavior; its body runs only when called or instantiated as appropriate.
- The print calls display the results. Compare these results with the method’s documented return type and the input used.
This example requires a newer interpreter than the local verification environment. Run it in a compatible Python installation and compare with the documented behavior.
What to Notice
Pay attention to the accepted input types, the returned value and the boundary behavior. Predict what changes if you replace the example input with an empty, zero, negative or missing value, where that value is meaningful for this operation.
If the task uses a library function, inspect its documented exceptions and return type before reusing it inside a larger function.
Where You Would Use This
Use the technique when it makes a real task easier to understand or safer to maintain. Check input and output behavior with small tests before combining it with larger application code.
Practice Exercise
Inspect one function with a forward reference and compare STRING with FORWARDREF.
Before running your edited example, write down the result you expect. Then test at least one valid boundary or deliberately invalid value, using appropriate exception handling where necessary.
Reference: official Python documentation for the complete API contract and version notes.
Common Beginner Mistakes
- Assuming that requesting string-form annotations makes arbitrary untrusted Python code safe to evaluate.
- Overlooking the documented condition: vALUE may evaluate annotation expressions, while even STRING and FORWARDREF formats are not guaranteed safe for untrusted code.
Key Takeaways
- Inspect annotations safely when building developer tooling.
- Reflection tools may need to examine annotations on functions.
- Inspect one function with a forward reference and compare STRING with FORWARDREF.