Skip to content

Commit f565a4a

Browse files
committed
gh-118974: Add dataclass_factory argument to make_dataclass
1 parent b72c748 commit f565a4a

File tree

2 files changed

+26
-6
lines changed

2 files changed

+26
-6
lines changed

Lib/dataclasses.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1492,7 +1492,7 @@ def _astuple_inner(obj, tuple_factory):
14921492
def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True,
14931493
repr=True, eq=True, order=False, unsafe_hash=False,
14941494
frozen=False, match_args=True, kw_only=False, slots=False,
1495-
weakref_slot=False, module=None):
1495+
weakref_slot=False, module=None, dataclass_factory=dataclass):
14961496
"""Return a new dynamically created dataclass.
14971497
14981498
The dataclass name will be 'cls_name'. 'fields' is an iterable
@@ -1572,11 +1572,11 @@ def exec_body_callback(ns):
15721572
if module is not None:
15731573
cls.__module__ = module
15741574

1575-
# Apply the normal decorator.
1576-
return dataclass(cls, init=init, repr=repr, eq=eq, order=order,
1577-
unsafe_hash=unsafe_hash, frozen=frozen,
1578-
match_args=match_args, kw_only=kw_only, slots=slots,
1579-
weakref_slot=weakref_slot)
1575+
# Apply the normal provided decorator.
1576+
return dataclass_factory(cls, init=init, repr=repr, eq=eq, order=order,
1577+
unsafe_hash=unsafe_hash, frozen=frozen,
1578+
match_args=match_args, kw_only=kw_only, slots=slots,
1579+
weakref_slot=weakref_slot)
15801580

15811581

15821582
def replace(obj, /, **changes):

Lib/test/test_dataclasses/__init__.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4204,6 +4204,26 @@ def test_funny_class_names_names(self):
42044204
C = make_dataclass(classname, ['a', 'b'])
42054205
self.assertEqual(C.__name__, classname)
42064206

4207+
def test_dataclass_factory_default(self):
4208+
C = make_dataclass('C', [('x', int)], dataclass_factory=dataclass)
4209+
c = C(10)
4210+
self.assertEqual(c.x, 10)
4211+
4212+
def test_dataclass_custom_factory(self):
4213+
def custom_dataclass(cls, *args, **kwargs):
4214+
def wrap(cls):
4215+
dc = dataclass(cls, *args, **kwargs)
4216+
dc.__custom__ = True
4217+
return dc
4218+
4219+
return wrap(cls)
4220+
4221+
C = make_dataclass('C', [('x', int)], dataclass_factory=custom_dataclass)
4222+
c = C(10)
4223+
self.assertEqual(c.x, 10)
4224+
self.assertEqual(c.__custom__, True)
4225+
4226+
42074227
class TestReplace(unittest.TestCase):
42084228
def test(self):
42094229
@dataclass(frozen=True)

0 commit comments

Comments
 (0)