Bug report
Bug/Inconsistency
Dataclass initialization errors out only if a lazily imported annotation that is represented as a string (such as when from __future__ import annotations is present) cannot be reified.
Examples
Repl without strs (success)
>>> from dataclasses import dataclass
>>> lazy import fake
>>> @dataclass
... class config:
... data: fake | None = None
...
>>>
Repl using str annotations (failure)
>>> from __future__ import annotations
>>> lazy import fake
>>> @dataclass
... class config:
... data: fake | None = None
...
Traceback (most recent call last):
File "<python-input-1>", line 1, in <module>
lazy import fake
ImportError: lazy import of 'fake' raised an exception during resolution
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<python-input-8>", line 1, in <module>
@dataclass
^^^^^^^^^
File "/home/breynoso/cpython/Lib/dataclasses.py", line 1458, in dataclass
return wrap(cls)
File "/home/breynoso/cpython/Lib/dataclasses.py", line 1448, in wrap
return _process_class(cls, init, repr, eq, order, unsafe_hash,
frozen, match_args, kw_only, slots,
weakref_slot)
File "/home/breynoso/cpython/Lib/dataclasses.py", line 1066, in _process_class
a_type_annotation = _get_type_from_annotation(type, cls)
File "/home/breynoso/cpython/Lib/dataclasses.py", line 809, in _get_type_from_annotation
root = getattr(root, path_item.strip(), None)
ModuleNotFoundError: No module named 'fake'
>>> from dataclasses import dataclass
>>> lazy import fake
>>> @dataclass
... class config:
... data: 'fake'
...
Traceback (most recent call last):
File "<python-input-1>", line 1, in <module>
lazy import fake
ImportError: lazy import of 'fake' raised an exception during resolution
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<python-input-3>", line 1, in <module>
@dataclass
^^^^^^^^^
File "/home/breynoso/cpython/Lib/dataclasses.py", line 1458, in dataclass
return wrap(cls)
File "/home/breynoso/cpython/Lib/dataclasses.py", line 1448, in wrap
return _process_class(cls, init, repr, eq, order, unsafe_hash,
frozen, match_args, kw_only, slots,
weakref_slot)
File "/home/breynoso/cpython/Lib/dataclasses.py", line 1066, in _process_class
a_type_annotation = _get_type_from_annotation(type, cls)
File "/home/breynoso/cpython/Lib/dataclasses.py", line 809, in _get_type_from_annotation
root = getattr(root, path_item.strip(), None)
ModuleNotFoundError: No module named 'fake'
CPython versions tested on:
3.15
Operating systems tested on:
Linux
Linked PRs
Bug report
Bug/Inconsistency
Dataclass initialization errors out only if a lazily imported annotation that is represented as a string (such as when
from __future__ import annotationsis present) cannot be reified.Examples
Repl without strs (success)
Repl using str annotations (failure)
CPython versions tested on:
3.15
Operating systems tested on:
Linux
Linked PRs