Skip to content

Commit c008676

Browse files
committed
Don't require __closure__ and __globals__ on annotate functions
1 parent fd6125d commit c008676

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

Lib/annotationlib.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -737,7 +737,8 @@ def call_annotate_function(annotate, format, *, owner=None, _is_evaluate=False):
737737
globals = _StringifierDict({}, format=format)
738738
is_class = isinstance(owner, type)
739739
closure, _ = _build_closure(
740-
annotate, owner, is_class, globals, allow_evaluation=False
740+
annotate, owner, is_class, globals,
741+
getattr(annotate, "__globals__", {}), allow_evaluation=False
741742
)
742743
try:
743744
annotate_code = annotate.__code__
@@ -790,7 +791,7 @@ def call_annotate_function(annotate, format, *, owner=None, _is_evaluate=False):
790791
format=format,
791792
)
792793
closure, cell_dict = _build_closure(
793-
annotate, owner, is_class, globals, allow_evaluation=True
794+
annotate, owner, is_class, globals, annotate_globals, allow_evaluation=True
794795
)
795796
try:
796797
annotate_code = annotate.__code__
@@ -828,7 +829,7 @@ def call_annotate_function(annotate, format, *, owner=None, _is_evaluate=False):
828829
format=format,
829830
)
830831
closure, cell_dict = _build_closure(
831-
annotate, owner, is_class, globals, allow_evaluation=False
832+
annotate, owner, is_class, globals, annotate_globals, allow_evaluation=False
832833
)
833834
func = types.FunctionType(
834835
annotate_code,
@@ -861,12 +862,12 @@ def call_annotate_function(annotate, format, *, owner=None, _is_evaluate=False):
861862
raise ValueError(f"Invalid format: {format!r}")
862863

863864

864-
def _build_closure(annotate, owner, is_class, stringifier_dict, *, allow_evaluation):
865-
if not annotate.__closure__:
865+
def _build_closure(annotate, owner, is_class, stringifier_dict, annotate_globals, *, allow_evaluation):
866+
if not (annotate_closure := getattr(annotate, "__closure__", None)):
866867
return None, None
867868
new_closure = []
868869
cell_dict = {}
869-
for name, cell in zip(annotate.__code__.co_freevars, annotate.__closure__, strict=True):
870+
for name, cell in zip(annotate.__code__.co_freevars, annotate_closure, strict=True):
870871
cell_dict[name] = cell
871872
new_cell = None
872873
if allow_evaluation:
@@ -881,7 +882,7 @@ def _build_closure(annotate, owner, is_class, stringifier_dict, *, allow_evaluat
881882
name,
882883
cell=cell,
883884
owner=owner,
884-
globals=annotate.__globals__,
885+
globals=annotate_globals,
885886
is_class=is_class,
886887
stringifier_dict=stringifier_dict,
887888
)

0 commit comments

Comments
 (0)