[Python-checkins] bpo-41515: Fix KeyError raised in get_type_hints (GH-25352)

gvanrossum webhook-mailer at python.org
Mon Apr 12 14:17:33 EDT 2021


https://github.com/python/cpython/commit/a9cf69df2e031d6157f01289f66ca9cf723ceb5c
commit: a9cf69df2e031d6157f01289f66ca9cf723ceb5c
branch: master
author: Karthikeyan Singaravelan <tir.karthi at gmail.com>
committer: gvanrossum <gvanrossum at gmail.com>
date: 2021-04-12T11:17:25-07:00
summary:

bpo-41515: Fix KeyError raised in get_type_hints (GH-25352)

Co-authored-by: Ken Jin <28750310+Fidget-Spinner at users.noreply.github.com>
Co-authored-by: efahl <36704995+efahl at users.noreply.github.com>

files:
A Misc/NEWS.d/next/Library/2021-04-12-06-01-10.bpo-41515.YaVReb.rst
M Lib/test/test_typing.py
M Lib/typing.py

diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py
index 062163ccf4b65..a6afd35944f2e 100644
--- a/Lib/test/test_typing.py
+++ b/Lib/test/test_typing.py
@@ -2267,6 +2267,12 @@ def test_no_isinstance(self):
         with self.assertRaises(TypeError):
             issubclass(int, ClassVar)
 
+    def test_bad_module(self):
+        # bpo-41515
+        class BadModule:
+            pass
+        BadModule.__module__ = 'bad' # Something not in sys.modules
+        assert(get_type_hints(BadModule), {})
 
 class FinalTests(BaseTestCase):
 
diff --git a/Lib/typing.py b/Lib/typing.py
index 583438e4740ab..dc2a7a478835d 100644
--- a/Lib/typing.py
+++ b/Lib/typing.py
@@ -1628,7 +1628,10 @@ def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
         hints = {}
         for base in reversed(obj.__mro__):
             if globalns is None:
-                base_globals = sys.modules[base.__module__].__dict__
+                try:
+                    base_globals = sys.modules[base.__module__].__dict__
+                except KeyError:
+                    continue
             else:
                 base_globals = globalns
             ann = base.__dict__.get('__annotations__', {})
diff --git a/Misc/NEWS.d/next/Library/2021-04-12-06-01-10.bpo-41515.YaVReb.rst b/Misc/NEWS.d/next/Library/2021-04-12-06-01-10.bpo-41515.YaVReb.rst
new file mode 100644
index 0000000000000..aef5c1791dfea
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2021-04-12-06-01-10.bpo-41515.YaVReb.rst
@@ -0,0 +1,2 @@
+Fix :exc:`KeyError` raised in :func:`typing.get_type_hints` due to
+synthetic modules that don't appear in ``sys.modules``.



More information about the Python-checkins mailing list