Skip to content

gh-135646: Raise consistent NameError exceptions in ForwardRef.evaluate() #135663

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 1 commit into from
Jun 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 4 additions & 1 deletion Lib/annotationlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ class Format(enum.IntEnum):


_sentinel = object()
# Following `NAME_ERROR_MSG` in `ceval_macros.h`:
_NAME_ERROR_MSG = "name '{name:.200}' is not defined"


# Slots shared by ForwardRef and _Stringifier. The __forward__ names must be
# preserved for compatibility with the old typing.ForwardRef class. The remaining
Expand Down Expand Up @@ -184,7 +187,7 @@ def evaluate(
elif is_forwardref_format:
return self
else:
raise NameError(arg)
raise NameError(_NAME_ERROR_MSG.format(name=arg), name=arg)
else:
code = self.__forward_code__
try:
Expand Down
4 changes: 3 additions & 1 deletion Lib/test/test_annotationlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -1650,9 +1650,11 @@ def test_name_lookup_without_eval(self):
with support.swap_attr(builtins, "int", dict):
self.assertIs(ForwardRef("int").evaluate(), dict)

with self.assertRaises(NameError):
with self.assertRaises(NameError, msg="name 'doesntexist' is not defined") as exc:
ForwardRef("doesntexist").evaluate()

self.assertEqual(exc.exception.name, "doesntexist")

def test_fwdref_invalid_syntax(self):
fr = ForwardRef("if")
with self.assertRaises(SyntaxError):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Raise consistent :exc:`NameError` exceptions in :func:`annotationlib.ForwardRef.evaluate`
Loading