Skip to content
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
6 changes: 5 additions & 1 deletion Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -806,7 +806,11 @@ def _get_type_from_annotation(annotation, cls):
path = match[1].split(".")
root = sys.modules.get(cls.__module__)
for path_item in path:
root = getattr(root, path_item.strip(), None)
try:
root = getattr(root, path_item.strip(), None)
except Exception:
# Like annotationlib, ignore lazy imports that cannot be resolved.
return None
if root is None:
return None

Expand Down
5 changes: 5 additions & 0 deletions Lib/test/test_dataclasses/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4525,6 +4525,11 @@ def test_classvar_module_level_import(self):
# won't exist on the instance.
self.assertNotIn('not_iv4', c.__dict__)

def test_lazy_import_annotations(self):
from test.test_dataclasses import dataclass_lazy_str as m
self.assertEqual([f.name for f in fields(m.C)], ['x', 'y'])
self.assertNotIsInstance(vars(m)['t'], types.LazyImportType)

def test_text_annotations(self):
from test.test_dataclasses import dataclass_textanno

Expand Down
1 change: 1 addition & 0 deletions Lib/test/test_dataclasses/dataclass_lazy_broken.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
raise RuntimeError("module fails to import")
12 changes: 12 additions & 0 deletions Lib/test/test_dataclasses/dataclass_lazy_str.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from __future__ import annotations

import dataclasses
lazy import typing as t
lazy from _dataclass_test_missing_module import Missing
lazy from test.test_dataclasses.dataclass_lazy_broken import Broken

@dataclasses.dataclass
class C:
x: Missing | None = None
y: Broken | None = None
cv: t.ClassVar[int] = 0
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
:func:`~dataclasses.dataclass` no longer fails when a string annotation names a
:ref:`lazy import <lazy-imports>` that cannot be resolved, matching the
behavior for non-string annotations.
Loading