gh-137969: Fix evaluation of ref.evaluate(format=Format.FORWARDREF) objects (#138075)

Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
This commit is contained in:
dr-carlos 2025-11-03 11:50:30 +10:30 committed by GitHub
parent e66f87ca73
commit 63e01d6bae
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 19 additions and 6 deletions

View file

@ -159,12 +159,12 @@ def evaluate(
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.
# between the locals and the globals.
type_param_scope = {}
if type_params is not None:
globals = dict(globals)
for param in type_params:
globals[param.__name__] = param
type_param_scope[param.__name__] = param
if self.__extra_names__:
locals = {**locals, **self.__extra_names__}
@ -172,6 +172,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):
@ -183,7 +185,7 @@ 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
@ -191,7 +193,7 @@ def evaluate(
# 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__,