]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-44468: Never skip base classes in `typing.get_type_hints()`, even with invalid...
authorwill-ca <willchencontact@gmail.com>
Sat, 26 Jun 2021 23:31:32 +0000 (23:31 +0000)
committerGitHub <noreply@github.com>
Sat, 26 Jun 2021 23:31:32 +0000 (16:31 -0700)
Lib/test/test_typing.py
Lib/typing.py
Misc/NEWS.d/next/Library/2021-06-23-19-02-00.bpo-44468.-klV5-.rst [new file with mode: 0644]

index cb198d6b75fd6e9fd28dde825fcf681dcfd034cf..e693883094d5c9ed9a27c10770bd679cb582ffe9 100644 (file)
@@ -2277,13 +2277,6 @@ 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
-        self.assertEqual(get_type_hints(BadModule), {})
-
 class FinalTests(BaseTestCase):
 
     def test_basics(self):
@@ -3033,6 +3026,24 @@ class GetTypeHintTests(BaseTestCase):
         # This previously raised an error under PEP 563.
         self.assertEqual(get_type_hints(Foo), {'x': str})
 
+    def test_get_type_hints_bad_module(self):
+        # bpo-41515
+        class BadModule:
+            pass
+        BadModule.__module__ = 'bad' # Something not in sys.modules
+        self.assertNotIn('bad', sys.modules)
+        self.assertEqual(get_type_hints(BadModule), {})
+
+    def test_get_type_hints_annotated_bad_module(self):
+        # See https://bugs.python.org/issue44468
+        class BadBase:
+            foo: tuple
+        class BadType(BadBase):
+            bar: list
+        BadType.__module__ = BadBase.__module__ = 'bad'
+        self.assertNotIn('bad', sys.modules)
+        self.assertEqual(get_type_hints(BadType), {'foo': tuple, 'bar': list})
+
 
 class GetUtilitiesTestCase(TestCase):
     def test_get_origin(self):
index 00a0df591cbfccd5c120314c0626a3d588913379..2287f0521a364f13723ee60f8e2f0329931c9627 100644 (file)
@@ -1701,10 +1701,7 @@ def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
         hints = {}
         for base in reversed(obj.__mro__):
             if globalns is None:
-                try:
-                    base_globals = sys.modules[base.__module__].__dict__
-                except KeyError:
-                    continue
+                base_globals = getattr(sys.modules.get(base.__module__, None), '__dict__', {})
             else:
                 base_globals = globalns
             ann = base.__dict__.get('__annotations__', {})
diff --git a/Misc/NEWS.d/next/Library/2021-06-23-19-02-00.bpo-44468.-klV5-.rst b/Misc/NEWS.d/next/Library/2021-06-23-19-02-00.bpo-44468.-klV5-.rst
new file mode 100644 (file)
index 0000000..78251c7
--- /dev/null
@@ -0,0 +1,2 @@
+:func:`typing.get_type_hints` now finds annotations in classes and base classes
+with unexpected ``__module__``. Previously, it skipped those MRO elements.