Skip to content

Commit a9cf69d

Browse files
tirkarthiFidget-Spinnerefahl
authored
bpo-41515: Fix KeyError raised in get_type_hints (GH-25352)
Co-authored-by: Ken Jin <[email protected]> Co-authored-by: efahl <[email protected]>
1 parent 852150d commit a9cf69d

File tree

3 files changed

+12
-1
lines changed

3 files changed

+12
-1
lines changed

Lib/test/test_typing.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2267,6 +2267,12 @@ def test_no_isinstance(self):
22672267
with self.assertRaises(TypeError):
22682268
issubclass(int, ClassVar)
22692269

2270+
def test_bad_module(self):
2271+
# bpo-41515
2272+
class BadModule:
2273+
pass
2274+
BadModule.__module__ = 'bad' # Something not in sys.modules
2275+
assert(get_type_hints(BadModule), {})
22702276

22712277
class FinalTests(BaseTestCase):
22722278

Lib/typing.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1628,7 +1628,10 @@ def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
16281628
hints = {}
16291629
for base in reversed(obj.__mro__):
16301630
if globalns is None:
1631-
base_globals = sys.modules[base.__module__].__dict__
1631+
try:
1632+
base_globals = sys.modules[base.__module__].__dict__
1633+
except KeyError:
1634+
continue
16321635
else:
16331636
base_globals = globalns
16341637
ann = base.__dict__.get('__annotations__', {})
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :exc:`KeyError` raised in :func:`typing.get_type_hints` due to
2+
synthetic modules that don't appear in ``sys.modules``.

0 commit comments

Comments
 (0)