diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py index ad644bb3128809..9cd73cc42510e7 100644 --- a/Lib/test/test_typing.py +++ b/Lib/test/test_typing.py @@ -7561,6 +7561,23 @@ def test_with_module(self): typing.evaluate_forward_ref( fwdref_module.fw,) + def test_evaluate_forward_ref_string_format(self): + # Test evaluating forward references in STRING format + # does not 'leak' internal names + # See https://github.com/python/cpython/issues/150641 + from annotationlib import Format, get_annotations + + def f(arg: unknown | str | int | list[str] | tuple[int, ...]): ... + + ref = get_annotations(f, format=Format.FORWARDREF)['arg'] + self.assertEqual( + typing.evaluate_forward_ref(ref, format=Format.STRING), + "unknown | str | int | list[str] | tuple[int, ...]", + ) + self.assertEqual( + typing.evaluate_forward_ref(ref, format=Format.STRING), + ref.__resolved_str__ + ) class CollectionsAbcTests(BaseTestCase): diff --git a/Lib/typing.py b/Lib/typing.py index 715d08e0e1603e..b2bc52e55d0fc7 100644 --- a/Lib/typing.py +++ b/Lib/typing.py @@ -1019,7 +1019,7 @@ def evaluate_forward_ref( """ if format == annotationlib.Format.STRING: - return forward_ref.__forward_arg__ + return forward_ref.__resolved_str__ if forward_ref.__forward_arg__ in _recursive_guard: return forward_ref diff --git a/Misc/NEWS.d/next/Library/2026-05-31-14-39-25.gh-issue-150641.LLIhd1.rst b/Misc/NEWS.d/next/Library/2026-05-31-14-39-25.gh-issue-150641.LLIhd1.rst new file mode 100644 index 00000000000000..3b9a3cbb3c2c26 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-05-31-14-39-25.gh-issue-150641.LLIhd1.rst @@ -0,0 +1,2 @@ +Fix evaluating forward references in STRING format can 'leak' internal names +in ``typing``.