8000 gh-114053: Fix another edge case involving `get_type_hints`, PEP 695 and PEP 563 by AlexWaygood · Pull Request #120272 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-114053: Fix another edge case involving get_type_hints, PEP 695 and PEP 563 #120272

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Jun 25, 2024
Next Next commit
gh-114053: Fix another edge case involving get_type_hints, PEP 695 …
…and PEP 563
  • Loading branch information
AlexWaygood committed Jun 8, 2024
commit 879abeba0b170dfa760f0e0115c98413055039bd
6 changes: 1 addition & 5 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -4866,11 +4866,7 @@ def test_pep695_generic_with_future_annotations(self):
self.assertIs(hints_for_A["z"].__args__[0], A_type_params[2])

hints_for_B = get_type_hints(ann_module695.B)
self.assertEqual(hints_for_B.keys(), {"x", "y", "z"})
self.assertEqual(
set(hints_for_B.values()) ^ set(ann_module695.B.__type_params__),
set()
)
self.assertEqual(hints_for_B, {"x": int, "y": str, "z": bytes})

hints_for_generic_function = get_type_hints(ann_module695.generic_function)
func_t_params = ann_module695.generic_function.__type_params__
Expand Down
6 changes: 3 additions & 3 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1064,11 +1064,11 @@ def _evaluate(self, globalns, localns, type_params=_sentinel, *, recursive_guard
# "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
globals_to_pass = {param.__name__: param for param in type_params} | globalns
else:
locals_to_pass = localns
globals_to_pass = globalns
type_ = _type_check(
eval(self.__forward_code__, globalns, locals_to_pass),
eval(self.__forward_code__, globals_to_pass, localns),
"Forward references must evaluate to types.",
is_argument=self.__forward_is_argument__,
allow_special_forms=self.__forward_is_class__,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fix edge-case bug where :func:`typing.get_type_hints` would produce
incorrect results if type parameters in a class scope were overridden by
assignments in a class scope and ``from __future__ import annotations``
semantics were enabled. Patch by Alex Waygood.
0