]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-135646: Raise consistent `NameError` exceptions in `ForwardRef.evaluate()` (#135663)
authorVictorien <65306057+Viicos@users.noreply.github.com>
Wed, 18 Jun 2025 13:00:55 +0000 (15:00 +0200)
committerGitHub <noreply@github.com>
Wed, 18 Jun 2025 13:00:55 +0000 (13:00 +0000)
Lib/annotationlib.py
Lib/test/test_annotationlib.py
Misc/NEWS.d/next/Library/2025-06-18-11-43-17.gh-issue-135646.r7ekEn.rst [new file with mode: 0644]

index 731817a997379997765f6668e78590bf5d9b65cb..c83a1573ccd3d1ee70069860a365d45c75ed4805 100644 (file)
@@ -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
@@ -184,7 +187,7 @@ class ForwardRef:
             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:
index fe091e52a86dc4d0d7f67c9b9ca4ba3ebac2ca88..ae0e73f08c5bd0909f8f998134a2690ece486330 100644 (file)
@@ -1650,9 +1650,11 @@ class TestForwardRefClass(unittest.TestCase):
         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):
diff --git a/Misc/NEWS.d/next/Library/2025-06-18-11-43-17.gh-issue-135646.r7ekEn.rst b/Misc/NEWS.d/next/Library/2025-06-18-11-43-17.gh-issue-135646.r7ekEn.rst
new file mode 100644 (file)
index 0000000..5fbd751
--- /dev/null
@@ -0,0 +1 @@
+Raise consistent :exc:`NameError` exceptions in :func:`annotationlib.ForwardRef.evaluate`