Get_type_hints() raises KeyError when class object has invalid __module__ attribute


I found typing.get_type_hints() raises a KeyError when the given class object has a wrong valued __module__ attribute (the value points non-existent module):

$ cat
import typing

class Foo:
    __module__ = 'unknown'

$ python
Traceback (most recent call last):
  File "", line 8, in <module>
  File "/Users/tkomiya/.pyenv/versions/3.8.3/lib/python3.8/", line 1223, in get_type_hints
    base_globals = sys.modules[base.__module__].__dict__
KeyError: 'unknown'

I confirmed the error on python-3.8.3. Is this expected behavior? I guess it might be better to re-raise ValueError instead. If so, I’ll post a bug report to bpo.

Additionally, I’d like to know what exceptions are typing.get_type_hints() raised.


I’ve tested on 3.6.11 and the behaviour is the same as you describe. It would certainly benefit from a better error message, although can’t understand how such a situation can arise.