diff --git a/Lib/annotationlib.py b/Lib/annotationlib.py index 5ad0893106a72b..c0b1d4395d14ed 100644 --- a/Lib/annotationlib.py +++ b/Lib/annotationlib.py @@ -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: diff --git a/Lib/test/test_annotationlib.py b/Lib/test/test_annotationlib.py index 13c6a2a584bc70..c3c245ddaf86d1 100644 --- a/Lib/test/test_annotationlib.py +++ b/Lib/test/test_annotationlib.py @@ -1053,6 +1053,21 @@ def f( }, ) + 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 index 00000000000000..9ebdfcb68aab65 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-05-04-15-39-25.gh-issue-119180.avZ3Hm.rst @@ -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`.