Skip to content

Commit d80b443

Browse files
authored
bpo-32279: Add additional params to make_dataclass(), pass through to dataclass(). (gh-5117)
1 parent ed7d429 commit d80b443

File tree

3 files changed

+26
-3
lines changed

3 files changed

+26
-3
lines changed

Lib/dataclasses.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -705,7 +705,8 @@ def _astuple_inner(obj, tuple_factory):
705705
return deepcopy(obj)
706706

707707

708-
def make_dataclass(cls_name, fields, *, bases=(), namespace=None):
708+
def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True,
709+
repr=True, eq=True, order=False, hash=None, frozen=False):
709710
"""Return a new dynamically created dataclass.
710711
711712
The dataclass name will be 'cls_name'. 'fields' is an iterable
@@ -723,6 +724,9 @@ class C(Base):
723724
b: int = field(init=False)
724725
725726
For the bases and namespace paremeters, see the builtin type() function.
727+
728+
The parameters init, repr, eq, order, hash, and frozen are passed to
729+
dataclass().
726730
"""
727731

728732
if namespace is None:
@@ -745,8 +749,8 @@ class C(Base):
745749

746750
namespace['__annotations__'] = anns
747751
cls = type(cls_name, bases, namespace)
748-
return dataclass(cls)
749-
752+
return dataclass(cls, init=init, repr=repr, eq=eq, order=order,
753+
hash=hash, frozen=frozen)
750754

751755
def replace(obj, **changes):
752756
"""Return a new object replacing specified fields with new values.

Lib/test/test_dataclasses.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2033,6 +2033,23 @@ def test_helper_make_dataclass_class_var(self):
20332033
self.assertEqual(C.y, 10)
20342034
self.assertEqual(C.z, 20)
20352035

2036+
def test_helper_make_dataclass_other_params(self):
2037+
C = make_dataclass('C',
2038+
[('x', int),
2039+
('y', ClassVar[int], 10),
2040+
('z', ClassVar[int], field(default=20)),
2041+
],
2042+
init=False)
2043+
# Make sure we have a repr, but no init.
2044+
self.assertNotIn('__init__', vars(C))
2045+
self.assertIn('__repr__', vars(C))
2046+
2047+
# Make sure random other params don't work.
2048+
with self.assertRaisesRegex(TypeError, 'unexpected keyword argument'):
2049+
C = make_dataclass('C',
2050+
[],
2051+
xxinit=False)
2052+
20362053
def test_helper_make_dataclass_no_types(self):
20372054
C = make_dataclass('Point', ['x', 'y', 'z'])
20382055
c = C(1, 2, 3)
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Add params to dataclasses.make_dataclasses(): init, repr, eq, order, hash,
2+
and frozen. Pass them through to dataclass().

0 commit comments

Comments
 (0)