gh-119180: Make the FORWARDREF format work with more kinds of runtime errors (#133407)

This commit is contained in:
Jelle Zijlstra 2025-05-05 08:21:11 -07:00 committed by GitHub
parent 4c56563f7a
commit 4e498d1e8b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 19 additions and 1 deletions

View 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:

View 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()

View file

@ -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`.