Skip to content
Merged
Changes from 1 commit
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
Next Next commit
Extract type param scope instead of copying globals dict
  • Loading branch information
dr-carlos committed Nov 4, 2025
commit 8708272e86ba62767a5eb23b171633a205728b24
19 changes: 12 additions & 7 deletions Lib/annotationlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,14 +161,17 @@ def evaluate(
# as a way of emulating annotation scopes when calling `eval()`
type_params = getattr(owner, "__type_params__", None)

# Type parameters exist in their own scope, which is logically
# between the locals and the globals. We simulate this by adding
# them to the globals. Similar reasoning applies to nonlocals stored in cells.
if type_params is not None or isinstance(self.__cell__, dict):
# Nonlocals logically sit between the locals and the globals. We simulate this
# by overriding the globals.
if isinstance(self.__cell__, dict):
globals = dict(globals)

# Type parameters exist in their own scope, which is logically
# between the locals and the globals.
type_param_scope = {}
if type_params is not None:
for param in type_params:
globals[param.__name__] = param
type_param_scope[param.__name__] = param
if isinstance(self.__cell__, dict):
for cell_name, cell_value in self.__cell__.items():
try:
Expand All @@ -182,6 +185,8 @@ def evaluate(
if arg.isidentifier() and not keyword.iskeyword(arg):
if arg in locals:
return locals[arg]
elif arg in type_param_scope:
return type_param_scope[arg]
elif arg in globals:
return globals[arg]
elif hasattr(builtins, arg):
Expand All @@ -193,15 +198,15 @@ def evaluate(
else:
code = self.__forward_code__
try:
return eval(code, globals=globals, locals=locals)
return eval(code, globals=globals, locals={**type_param_scope, **locals})
except Exception:
if not is_forwardref_format:
raise

# All variables, in scoping order, should be checked before
# triggering __missing__ to create a _Stringifier.
new_locals = _StringifierDict(
{**builtins.__dict__, **globals, **locals},
{**builtins.__dict__, **globals, **type_param_scope, **locals},
globals=globals,
owner=owner,
is_class=self.__forward_is_class__,
Expand Down