Skip to content

Commit 852150d

Browse files
bpo-42904: Fix get_type_hints for class local namespaces (GH-24201)
1 parent 37a5e22 commit 852150d

File tree

3 files changed

+12
-2
lines changed

3 files changed

+12
-2
lines changed

Lib/test/test_typing.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2874,7 +2874,7 @@ def test_get_type_hints_classes(self):
28742874
{'x': int, 'y': int})
28752875
self.assertEqual(gth(mod_generics_cache.B),
28762876
{'my_inner_a1': mod_generics_cache.B.A,
2877-
'my_inner_a2': mod_generics_cache.A,
2877+
'my_inner_a2': mod_generics_cache.B.A,
28782878
'my_outer_a': mod_generics_cache.A})
28792879

28802880
def test_respect_no_type_check(self):
@@ -3010,6 +3010,13 @@ def __iand__(self, other: Const["MySet[T]"]) -> "MySet[T]":
30103010
{'other': MySet[T], 'return': MySet[T]}
30113011
)
30123012

3013+
def test_get_type_hints_classes(self):
3014+
class Foo:
3015+
y = str
3016+
x: y
3017+
# This previously raised an error under PEP 563.
3018+
self.assertEqual(get_type_hints(Foo), {'x': str})
3019+
30133020

30143021
class GetUtilitiesTestCase(TestCase):
30153022
def test_get_origin(self):

Lib/typing.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1632,12 +1632,13 @@ def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
16321632
else:
16331633
base_globals = globalns
16341634
ann = base.__dict__.get('__annotations__', {})
1635+
base_locals = dict(vars(base)) if localns is None else localns
16351636
for name, value in ann.items():
16361637
if value is None:
16371638
value = type(None)
16381639
if isinstance(value, str):
16391640
value = ForwardRef(value, is_argument=False)
1640-
value = _eval_type(value, base_globals, localns)
1641+
value = _eval_type(value, base_globals, base_locals)
16411642
hints[name] = value
16421643
return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}
16431644

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:func:`typing.get_type_hints` now checks the local namespace of a class when
2+
evaluating :pep:`563` annotations inside said class.

0 commit comments

Comments
 (0)