[Python-checkins] Added kw_only parameter to make_dataclasses. (GH-29679)

ericvsmith webhook-mailer at python.org
Sat Nov 20 18:26:09 EST 2021


https://github.com/python/cpython/commit/f7638dd0f90b2afd9295ee179119f4a29859953a
commit: f7638dd0f90b2afd9295ee179119f4a29859953a
branch: main
author: Eric V. Smith <ericvsmith at users.noreply.github.com>
committer: ericvsmith <ericvsmith at users.noreply.github.com>
date: 2021-11-20T18:25:56-05:00
summary:

Added kw_only parameter to make_dataclasses. (GH-29679)

files:
A Misc/NEWS.d/next/Library/2021-11-20-17-04-25.bpo-45803.wSgFOy.rst
M Lib/dataclasses.py
M Lib/test/test_dataclasses.py

diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py
index 1e98bf9b9bb97..aca60501d0e0f 100644
--- a/Lib/dataclasses.py
+++ b/Lib/dataclasses.py
@@ -1326,7 +1326,7 @@ def _astuple_inner(obj, tuple_factory):
 
 def make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True,
                    repr=True, eq=True, order=False, unsafe_hash=False,
-                   frozen=False, match_args=True, slots=False):
+                   frozen=False, match_args=True, kw_only=False, slots=False):
     """Return a new dynamically created dataclass.
 
     The dataclass name will be 'cls_name'.  'fields' is an iterable
@@ -1393,7 +1393,7 @@ def exec_body_callback(ns):
     # Apply the normal decorator.
     return dataclass(cls, init=init, repr=repr, eq=eq, order=order,
                      unsafe_hash=unsafe_hash, frozen=frozen,
-                     match_args=match_args, slots=slots)
+                     match_args=match_args, kw_only=kw_only, slots=slots)
 
 
 def replace(obj, /, **changes):
diff --git a/Lib/test/test_dataclasses.py b/Lib/test/test_dataclasses.py
index bbbb8e6c6395b..b00d0484d387e 100644
--- a/Lib/test/test_dataclasses.py
+++ b/Lib/test/test_dataclasses.py
@@ -3864,5 +3864,16 @@ class A:
                 c: int = 1
                 d: int
 
+    def test_make_dataclass(self):
+        A = make_dataclass("A", ['a'], kw_only=True)
+        self.assertTrue(fields(A)[0].kw_only)
+
+        B = make_dataclass("B",
+                           ['a', ('b', int, field(kw_only=False))],
+                           kw_only=True)
+        self.assertTrue(fields(B)[0].kw_only)
+        self.assertFalse(fields(B)[1].kw_only)
+
+
 if __name__ == '__main__':
     unittest.main()
diff --git a/Misc/NEWS.d/next/Library/2021-11-20-17-04-25.bpo-45803.wSgFOy.rst b/Misc/NEWS.d/next/Library/2021-11-20-17-04-25.bpo-45803.wSgFOy.rst
new file mode 100644
index 0000000000000..77479d7db476b
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2021-11-20-17-04-25.bpo-45803.wSgFOy.rst
@@ -0,0 +1 @@
+Added missing kw_only parameter to dataclasses.make_dataclass().



More information about the Python-checkins mailing list