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
20 changes: 14 additions & 6 deletions Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -708,9 +708,10 @@ def _astuple_inner(obj, tuple_factory):
def make_dataclass(cls_name, fields, *, bases=(), namespace=None):
"""Return a new dynamically created dataclass.

The dataclass name will be 'cls_name'. 'fields' is an interable
of either (name, type) or (name, type, Field) objects. Field
objects are created by calling 'field(name, type [, Field])'.
The dataclass name will be 'cls_name'. 'fields' is an iterable
of either (name), (name, type) or (name, type, Field) objects. If type is
omitted, use the string 'typing.Any'. Field objects are created by
calling 'field(name, type [, Field])'.

C = make_class('C', [('a', int', ('b', int, Field(init=False))], bases=Base)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here is a typo/unmatched paren: it should be ('a', int), not ('a', int'


Expand All @@ -730,12 +731,19 @@ class C(Base):
# Copy namespace since we're going to mutate it.
namespace = namespace.copy()

anns = collections.OrderedDict((name, tp) for name, tp, *_ in fields)
namespace['__annotations__'] = anns
anns = collections.OrderedDict()
for item in fields:
if len(item) == 3:
if isinstance(item, str):
name = item
tp = 'typing.Any'
elif len(item) == 2:
name, tp, = item
elif len(item) == 3:
name, tp, spec = item
namespace[name] = spec
anns[name] = tp

namespace['__annotations__'] = anns
cls = type(cls_name, bases, namespace)
return dataclass(cls)

Expand Down
14 changes: 14 additions & 0 deletions Lib/test/test_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -2033,6 +2033,20 @@ def test_helper_make_dataclass_class_var(self):
self.assertEqual(C.y, 10)
self.assertEqual(C.z, 20)

def test_helper_make_dataclass_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'})

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',
'y': int,
'z': 'typing.Any'})

class TestDocString(unittest.TestCase):
def assertDocStrEqual(self, a, b):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Make type information optional on dataclasses.make_dataclass(). If omitted,
the string 'typing.Any' is used.