Skip to content

Commit 3e80ba7

Browse files
author
Lukasz Langa
committed
get_type_hints(): find the right globalns for classes
This makes the default behavior (without specifying `globalns` manually) more predictable for users. Implementation assumes the class has a `__module__` attribute and that module is present in `sys.modules`. This is backwards compatible, will just raise fewer exceptions in naive user code.
1 parent cc89ce8 commit 3e80ba7

File tree

2 files changed

+5
-2
lines changed

2 files changed

+5
-2
lines changed

src/test_typing.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1660,7 +1660,7 @@ def test_get_type_hints_modules(self):
16601660

16611661
@skipUnless(PY36, 'Python 3.6 required')
16621662
def test_get_type_hints_classes(self):
1663-
self.assertEqual(gth(ann_module.C, ann_module.__dict__),
1663+
self.assertEqual(gth(ann_module.C), # gth will find the right globalns
16641664
{'y': Optional[ann_module.C]})
16651665
self.assertIsInstance(gth(ann_module.j_class), dict)
16661666
self.assertEqual(gth(ann_module.M), {'123': 123, 'o': type})

src/typing.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1494,7 +1494,10 @@ def get_type_hints(obj, globalns=None, localns=None):
14941494
if getattr(obj, '__no_type_check__', None):
14951495
return {}
14961496
if globalns is None:
1497-
globalns = getattr(obj, '__globals__', {})
1497+
if isinstance(obj, type):
1498+
globalns = vars(sys.modules[obj.__module__])
1499+
else:
1500+
globalns = getattr(obj, '__globals__', {})
14981501
if localns is None:
14991502
localns = globalns
15001503
elif localns is None:

0 commit comments

Comments
 (0)