diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py index af26991ddfa399..8c8173a73f68cf 100644 --- a/Lib/dataclasses.py +++ b/Lib/dataclasses.py @@ -1551,13 +1551,15 @@ class C(Base): annotations[name] = tp def annotate_method(format): - if format != 1: - raise NotImplementedError - from typing import Any - return { + from typing import Any, _convert_to_source + ann_dict = { ann: Any if t is any_marker else t for ann, t in annotations.items() } + if format == 1 or format == 2: + return ann_dict + else: + return _convert_to_source(ann_dict) # Update 'ns' with the user-supplied namespace plus our calculated values. def exec_body_callback(ns): diff --git a/Lib/test/test_dataclasses/__init__.py b/Lib/test/test_dataclasses/__init__.py index 6934e88d9d338c..09ad211d22d5a1 100644 --- a/Lib/test/test_dataclasses/__init__.py +++ b/Lib/test/test_dataclasses/__init__.py @@ -4159,16 +4159,34 @@ def test_no_types(self): C = make_dataclass('Point', ['x', 'y', 'z']) c = C(1, 2, 3) self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3}) - self.assertEqual(C.__annotations__, {'x': 'typing.Any', - 'y': 'typing.Any', - 'z': 'typing.Any'}) + self.assertEqual(C.__annotations__, {'x': typing.Any, + 'y': typing.Any, + 'z': typing.Any}) C = make_dataclass('Point', ['x', ('y', int), 'z']) c = C(1, 2, 3) self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3}) - self.assertEqual(C.__annotations__, {'x': 'typing.Any', + self.assertEqual(C.__annotations__, {'x': typing.Any, 'y': int, - 'z': 'typing.Any'}) + 'z': typing.Any}) + + def test_no_types_get_annotations(self): + from annotationlib import Format, get_annotations + + C = make_dataclass('C', ['x', ('y', int), 'z']) + + self.assertEqual( + get_annotations(C, format=Format.VALUE), + {'x': typing.Any, 'y': int, 'z': typing.Any}, + ) + self.assertEqual( + get_annotations(C, format=Format.FORWARDREF), + {'x': typing.Any, 'y': int, 'z': typing.Any}, + ) + self.assertEqual( + get_annotations(C, format=Format.SOURCE), + {'x': 'typing.Any', 'y': 'int', 'z': 'typing.Any'}, + ) def test_module_attr(self): self.assertEqual(ByMakeDataClass.__module__, __name__) diff --git a/Misc/NEWS.d/next/Library/2024-09-18-09-15-40.gh-issue-82129.GQwt3u.rst b/Misc/NEWS.d/next/Library/2024-09-18-09-15-40.gh-issue-82129.GQwt3u.rst new file mode 100644 index 00000000000000..a826e32da1c2e9 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2024-09-18-09-15-40.gh-issue-82129.GQwt3u.rst @@ -0,0 +1,3 @@ +Fix :exc:`NameError` happenning on :func:`dataclasses.dataclass` created by +:func:`dataclasses.make_dataclass` with un-annotated fields when +:func:`typing.get_type_hints` was called on it.