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

This commit is contained in:
Victorien 2025-06-18 15:00:55 +02:00 committed by GitHub
parent 9877d191f4
commit 343719d98e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 8 additions and 2 deletions

View file

@ -27,6 +27,9 @@ class Format(enum.IntEnum):
_sentinel = object() _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 # Slots shared by ForwardRef and _Stringifier. The __forward__ names must be
# preserved for compatibility with the old typing.ForwardRef class. The remaining # preserved for compatibility with the old typing.ForwardRef class. The remaining
@ -184,7 +187,7 @@ class ForwardRef:
elif is_forwardref_format: elif is_forwardref_format:
return self return self
else: else:
raise NameError(arg) raise NameError(_NAME_ERROR_MSG.format(name=arg), name=arg)
else: else:
code = self.__forward_code__ code = self.__forward_code__
try: try:

View file

@ -1650,9 +1650,11 @@ class TestForwardRefClass(unittest.TestCase):
with support.swap_attr(builtins, "int", dict): with support.swap_attr(builtins, "int", dict):
self.assertIs(ForwardRef("int").evaluate(), 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() ForwardRef("doesntexist").evaluate()
self.assertEqual(exc.exception.name, "doesntexist")
def test_fwdref_invalid_syntax(self): def test_fwdref_invalid_syntax(self):
fr = ForwardRef("if") fr = ForwardRef("if")
with self.assertRaises(SyntaxError): with self.assertRaises(SyntaxError):

View file

@ -0,0 +1 @@
Raise consistent :exc:`NameError` exceptions in :func:`annotationlib.ForwardRef.evaluate`