]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-41515: Fix KeyError raised in get_type_hints (GH-25352)
authorKarthikeyan Singaravelan <tir.karthi@gmail.com>
Mon, 12 Apr 2021 18:17:25 +0000 (23:47 +0530)
committerGitHub <noreply@github.com>
Mon, 12 Apr 2021 18:17:25 +0000 (11:17 -0700)
Co-authored-by: Ken Jin <28750310+Fidget-Spinner@users.noreply.github.com>
Co-authored-by: efahl <36704995+efahl@users.noreply.github.com>
Lib/test/test_typing.py
Lib/typing.py
Misc/NEWS.d/next/Library/2021-04-12-06-01-10.bpo-41515.YaVReb.rst [new file with mode: 0644]

index 062163ccf4b65ba7d986927db02989c7a06741fa..a6afd35944f2e73b9c6662a0a928a4ec6525ac3e 100644 (file)
@@ -2267,6 +2267,12 @@ class ClassVarTests(BaseTestCase):
         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):
 
index 583438e4740ab19c181825ef7a3e2753f3d5284c..dc2a7a478835dbca51f1b6fe7006c057892ee484 100644 (file)
@@ -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 (file)
index 0000000..aef5c17
--- /dev/null
@@ -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``.