summaryrefslogtreecommitdiffstats
path: root/Lib/typing.py
diff options
context:
space:
mode:
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>2024-06-25 16:30:08 (GMT)
committerGitHub <noreply@github.com>2024-06-25 16:30:08 (GMT)
commitf4f8a714b5fe0e83d63c54cdf39e8d8920047e6c (patch)
treefb85b7735edb71983732d494c4dce61690d3773c /Lib/typing.py
parent899dfbaf0e62c71885eced4747d7d4c93b7bbd4f (diff)
downloadcpython-f4f8a714b5fe0e83d63c54cdf39e8d8920047e6c.zip
cpython-f4f8a714b5fe0e83d63c54cdf39e8d8920047e6c.tar.gz
cpython-f4f8a714b5fe0e83d63c54cdf39e8d8920047e6c.tar.bz2
[3.13] gh-114053: Fix another edge case involving `get_type_hints`, PEP 695 and PEP 563 (GH-120272) (#121003)
Co-authored-by: Alex Waygood <Alex.Waygood@Gmail.com>
Diffstat (limited to 'Lib/typing.py')
-rw-r--r--Lib/typing.py23
1 files changed, 16 insertions, 7 deletions
diff --git a/Lib/typing.py b/Lib/typing.py
index d09b320..fda0b2d 100644
--- a/Lib/typing.py
+++ b/Lib/typing.py
@@ -1061,15 +1061,24 @@ class ForwardRef(_Final, _root=True):
globalns = getattr(
sys.modules.get(self.__forward_module__, None), '__dict__', globalns
)
+
+ # type parameters require some special handling,
+ # as they exist in their own scope
+ # but `eval()` does not have a dedicated parameter for that scope.
+ # For classes, names in type parameter scopes should override
+ # names in the global scope (which here are called `localns`!),
+ # but should in turn be overridden by names in the class scope
+ # (which here are called `globalns`!)
if type_params:
- # "Inject" type parameters into the local namespace
- # (unless they are shadowed by assignments *in* the local namespace),
- # as a way of emulating annotation scopes when calling `eval()`
- locals_to_pass = {param.__name__: param for param in type_params} | localns
- else:
- locals_to_pass = localns
+ globalns, localns = dict(globalns), dict(localns)
+ for param in type_params:
+ param_name = param.__name__
+ if not self.__forward_is_class__ or param_name not in globalns:
+ globalns[param_name] = param
+ localns.pop(param_name, None)
+
type_ = _type_check(
- eval(self.__forward_code__, globalns, locals_to_pass),
+ eval(self.__forward_code__, globalns, localns),
"Forward references must evaluate to types.",
is_argument=self.__forward_is_argument__,
allow_special_forms=self.__forward_is_class__,