Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions Lib/annotationlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -855,6 +855,11 @@ def _build_closure(annotate, owner, is_class, stringifier_dict, *, allow_evaluat
cell_dict = {}
for name, cell in zip(annotate.__code__.co_freevars, annotate.__closure__, strict=True):
cell_dict[name] = cell
# This is an internal name for ensuring we get the correct annotations,
# so do not replace the original cell.
if name == "__conditional_annotations__":
new_closure.append(cell)
continue
new_cell = None
if allow_evaluation:
try:
Expand Down
16 changes: 16 additions & 0 deletions Lib/test/test_annotationlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -1206,6 +1206,22 @@ def __call__(self):
with self.subTest(format=format, obj=obj):
self.assertEqual(get_annotations(obj, format=format), {})

def test_conditional_annotations(self):
class ConditionalAnnotations:
x: int
if False:
y: str

self.assertEqual(get_annotations(ConditionalAnnotations), {"x": int})
self.assertEqual(
get_annotations(ConditionalAnnotations, format=Format.FORWARDREF),
{"x": int},
)
self.assertEqual(
get_annotations(ConditionalAnnotations, format=Format.STRING),
{"x": "int"},
)

def test_pep695_generic_class_with_future_annotations(self):
ann_module695 = inspect_stringized_annotations_pep695
A_annotations = get_annotations(ann_module695.A, eval_str=True)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix bug where :mod:`annotationlib` could return annotations located in code
blocks that are not executed at runtime.
Loading