]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-119180: Make the FORWARDREF format work with more kinds of runtime errors (#133407)
authorJelle Zijlstra <jelle.zijlstra@gmail.com>
Mon, 5 May 2025 15:21:11 +0000 (08:21 -0700)
committerGitHub <noreply@github.com>
Mon, 5 May 2025 15:21:11 +0000 (08:21 -0700)
Lib/annotationlib.py
Lib/test/test_annotationlib.py
Misc/NEWS.d/next/Library/2025-05-04-15-39-25.gh-issue-119180.avZ3Hm.rst [new file with mode: 0644]

index 5ad0893106a72b8ff853c24df7cc4e06cabad96c..c0b1d4395d14ed1a8c72a6520cfed51ee042dff2 100644 (file)
@@ -868,7 +868,7 @@ def get_annotations(
             # For FORWARDREF, we use __annotations__ if it exists
             try:
                 ann = _get_dunder_annotations(obj)
-            except NameError:
+            except Exception:
                 pass
             else:
                 if ann is not None:
index 13c6a2a584bc7055d897b21960ed1762e81ed009..c3c245ddaf86d1b0b4faec663a93568419c49531 100644 (file)
@@ -1053,6 +1053,21 @@ class TestGetAnnotations(unittest.TestCase):
             },
         )
 
+    def test_partial_evaluation_error(self):
+        def f(x: range[1]):
+            pass
+        with self.assertRaisesRegex(
+            TypeError, "type 'range' is not subscriptable"
+        ):
+            f.__annotations__
+
+        self.assertEqual(
+            get_annotations(f, format=Format.FORWARDREF),
+            {
+                "x": support.EqualToForwardRef("range[1]", owner=f),
+            },
+        )
+
     def test_partial_evaluation_cell(self):
         obj = object()
 
diff --git a/Misc/NEWS.d/next/Library/2025-05-04-15-39-25.gh-issue-119180.avZ3Hm.rst b/Misc/NEWS.d/next/Library/2025-05-04-15-39-25.gh-issue-119180.avZ3Hm.rst
new file mode 100644 (file)
index 0000000..9ebdfcb
--- /dev/null
@@ -0,0 +1,3 @@
+Make :func:`annotationlib.get_annotations` succeed with the ``FORWARDREF``
+format if evaluating the annotations throws an exception other than
+:exc:`NameError` or :exc:`AttributeError`.