Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Fix NameError
  • Loading branch information
sobolevn committed Sep 18, 2024
commit 642f8498845592bf8e7197f1aedfd0c894bbe589
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.