Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.
Sign upTypedDict inheritance doesn't work with get_type_hints and postponed evaluation of annotations across modules #737
Comments
|
Hi @keithblaha, can you also file this on bugs.python.org? It is relevant for Python 3.10 which will turn on this behavior by default. (In fact it probably isn't going to be fixed anywhere except in the 3.9 and 3.10 stdlib versions of typing.py -- and maybe 3.8.) |
I came across this issue while using inheritance to express required keys in a
TypedDict, as is recommended by the docs.It's most easily explained by a minimal example I cooked up. Let's say we have a module
foo.py:And another module
bar.py:Note that both
foo.pyandbar.pyhave adopted postponed evaluation of annotations (PEP 563) by using the__future__import.If we execute
bar.py, we get the error messageNameError: name 'Optional' is not defined.This is due to the combination of:
get_type_hintsrelies on the MRO to resolve types: https://github.com/python/cpython/blob/3.7/Lib/typing.py#L970TypedDictdoes not preserve the original bases, soFoois not in the MRO forBar:typing/typing_extensions/src_py3/typing_extensions.py
Line 1652 in d79edde
Thus,
get_type_hintsis unable to resolve the types for annotations that are only imported infoo.py.I ran this example using typing_extensions 3.7.4.2 (released via #709) and Python 3.7.3, but it seems like this would be an issue using the current main branches of both repositories as well.
I'm wondering what the right approach is to tackling this issue. It is of course solvable by defining
Barinfoo.pyinstead, but it isn't ideal or intuitive to always need to inherit from aTypedDictin the same module.I was thinking that similarly to
__required_keys__and__optional_keys__, theTypedDictcould preserve its original bases in a new dunder attribute, andget_type_hintscould work off of that instead of MRO when it is dealing with aTypedDict. I would be willing to contribute the PRs to implement this if the design is acceptable, but am open to other ideas as well.