Skip to content

Commit 96f619f

Browse files
gh-124206: Fix calling get_annotate_function() on static types (#124208)
Fixes #124206. No news entry because the bug this fixes was never released.
1 parent 3b6bfa7 commit 96f619f

File tree

3 files changed

+45
-1
lines changed

3 files changed

+45
-1
lines changed

Lib/annotationlib.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -575,7 +575,11 @@ def get_annotate_function(obj):
575575
Returns the __annotate__ function or None.
576576
"""
577577
if isinstance(obj, type):
578-
return _BASE_GET_ANNOTATE(obj)
578+
try:
579+
return _BASE_GET_ANNOTATE(obj)
580+
except AttributeError:
581+
# AttributeError is raised for static types.
582+
return None
579583
return getattr(obj, "__annotate__", None)
580584

581585

Lib/test/test_annotationlib.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -928,6 +928,27 @@ class D(metaclass=Meta):
928928
self.assertIs(annotate_func, None)
929929

930930

931+
class TestGetAnnotateFunction(unittest.TestCase):
932+
def test_static_class(self):
933+
self.assertIsNone(get_annotate_function(object))
934+
self.assertIsNone(get_annotate_function(int))
935+
936+
def test_unannotated_class(self):
937+
class C:
938+
pass
939+
940+
self.assertIsNone(get_annotate_function(C))
941+
942+
D = type("D", (), {})
943+
self.assertIsNone(get_annotate_function(D))
944+
945+
def test_annotated_class(self):
946+
class C:
947+
a: int
948+
949+
self.assertEqual(get_annotate_function(C)(Format.VALUE), {"a": int})
950+
951+
931952
class TestAnnotationLib(unittest.TestCase):
932953
def test__all__(self):
933954
support.check__all__(self, annotationlib)

Lib/test/test_typing.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7043,6 +7043,25 @@ def h(x: collections.abc.Callable[P, int]): ...
70437043
self.assertEqual(get_type_hints(g), {'x': collections.abc.Callable[..., int]})
70447044
self.assertEqual(get_type_hints(h), {'x': collections.abc.Callable[P, int]})
70457045

7046+
def test_get_type_hints_format(self):
7047+
class C:
7048+
x: undefined
7049+
7050+
with self.assertRaises(NameError):
7051+
get_type_hints(C)
7052+
7053+
with self.assertRaises(NameError):
7054+
get_type_hints(C, format=annotationlib.Format.VALUE)
7055+
7056+
annos = get_type_hints(C, format=annotationlib.Format.FORWARDREF)
7057+
self.assertIsInstance(annos, dict)
7058+
self.assertEqual(list(annos), ['x'])
7059+
self.assertIsInstance(annos['x'], annotationlib.ForwardRef)
7060+
self.assertEqual(annos['x'].__arg__, 'undefined')
7061+
7062+
self.assertEqual(get_type_hints(C, format=annotationlib.Format.SOURCE),
7063+
{'x': 'undefined'})
7064+
70467065

70477066
class GetUtilitiesTestCase(TestCase):
70487067
def test_get_origin(self):

0 commit comments

Comments
 (0)