Skip to content

bpo-44468: Never skip base classes in typing.get_type_hints(), even with invalid .__module__. #26862

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 26, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 18 additions & 7 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -2277,13 +2277,6 @@ 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
self.assertEqual(get_type_hints(BadModule), {})

class FinalTests(BaseTestCase):

def test_basics(self):
Expand Down Expand Up @@ -3033,6 +3026,24 @@ class Foo:
# 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):
Expand Down
5 changes: 1 addition & 4 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__', {})
Expand Down
Original file line number Diff line number Diff line change
@@ -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.