Skip to content

Commit

Permalink
Fix NameError
Browse files Browse the repository at this point in the history
  • Loading branch information
sobolevn committed Sep 18, 2024
1 parent de409ad commit 642f849
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 9 deletions.
10 changes: 6 additions & 4 deletions Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
28 changes: 23 additions & 5 deletions Lib/test/test_dataclasses/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)
Expand Down
Original file line number Diff line number Diff line change
@@ -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.

0 comments on commit 642f849

Please sign in to comment.