Title: get_type_hints fails if there are un-annotated fields in a dataclass
Type: behavior Stage:
Components: Versions: Python 3.8, Python 3.7
Status: open Resolution:
Dependencies: Superseder:
Assigned To: eric.smith Nosy List: arne, eric.smith, levkivskyi
Priority: normal Keywords:

Created on 2019-08-26 06:29 by arne, last changed 2019-09-02 09:13 by levkivskyi.

Messages (2)
msg350488 - (view) Author: Arne Recknagel (arne) Date: 2019-08-26 06:29
When declaring a dataclass with make_dataclass, it is valid to omit type information for fields. __annotations__ understands it and just adds typing.Any, but typing.get_type_hints fails with a cryptic error message:

>>> import dataclasses
>>> import typing
>>> A = dataclasses.make_dataclass('A', ['a_var'])
>>> A.__annotations__
{'a_var': 'typing.Any'}
>>> typing.get_type_hints(A)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/user/venvs/python_3.7/lib/python3.7/", line 973, in get_type_hints
    value = _eval_type(value, base_globals, localns)
  File "/user/venvs/python_3.7/lib/python3.7/", line 260, in _eval_type
    return t._evaluate(globalns, localns)
  File "/user/venvs/python_3.7/lib/python3.7/", line 464, in _evaluate
    eval(self.__forward_code__, globalns, localns),
  File "<string>", line 1, in <module>
NameError: name 'typing' is not defined

Adding typing.Any explicitly is an obvious workaround:

>>> B = dataclasses.make_dataclass('B', [('a_var', typing.Any)])
>>> typing.get_type_hints(B)
{'a_var': typing.Any}

There is already a bug filed regarding datalcasses and get_type_hints which might be related:
msg350973 - (view) Author: Ivan Levkivskyi (levkivskyi) * (Python committer) Date: 2019-09-02 09:13
It looks like will fix also this one.
Date User Action Args
2019-09-02 09:13:00levkivskyisetnosy: + levkivskyi
messages: + msg350973
2019-08-26 08:34:57eric.smithsetassignee: eric.smith
2019-08-26 06:29:12arnecreate