[Python-checkins] Add What's New for dataclass keyword-only parameters. (GH-28158) (GH-28163)
ericvsmith
webhook-mailer at python.org
Sat Sep 4 14:59:33 EDT 2021
https://github.com/python/cpython/commit/9438443a5fff6f96af48ea0eda0ca4e3fa67ae52
commit: 9438443a5fff6f96af48ea0eda0ca4e3fa67ae52
branch: 3.10
author: Miss Islington (bot) <31488909+miss-islington at users.noreply.github.com>
committer: ericvsmith <ericvsmith at users.noreply.github.com>
date: 2021-09-04T14:59:29-04:00
summary:
Add What's New for dataclass keyword-only parameters. (GH-28158) (GH-28163)
(cherry picked from commit a1ba3597d2d2dd5e5d73f42b1174ab5e0a2cd224)
Co-authored-by: Eric V. Smith <ericvsmith at users.noreply.github.com>
Co-authored-by: Eric V. Smith <ericvsmith at users.noreply.github.com>
files:
M Doc/whatsnew/3.10.rst
diff --git a/Doc/whatsnew/3.10.rst b/Doc/whatsnew/3.10.rst
index 129c0f77bf895..068eb7676324d 100644
--- a/Doc/whatsnew/3.10.rst
+++ b/Doc/whatsnew/3.10.rst
@@ -983,9 +983,68 @@ they are provided by the underlying curses library.
dataclasses
-----------
-Add ``slots`` parameter in :func:`dataclasses.dataclass` decorator.
+__slots__
+~~~~~~~~~
+
+Added ``slots`` parameter in :func:`dataclasses.dataclass` decorator.
(Contributed by Yurii Karabas in :issue:`42269`)
+Keyword-only fields
+~~~~~~~~~~~~~~~~~~~
+
+dataclassses now supports fields that are keyword-only in the
+generated __init__ method. There are a number of ways of specifying
+keyword-only fields.
+
+You can say that every field is keyword-only:
+
+.. code-block:: python
+
+ from dataclasses import dataclass
+
+ @dataclass(kw_only=True)
+ class Birthday:
+ name: str
+ birthday: datetime.date
+
+Both ``name`` and ``birthday`` are keyword-only parameters to the
+generated __init__ method.
+
+You can specify keyword-only on a per-field basis:
+
+.. code-block:: python
+
+ from dataclasses import dataclass
+
+ @dataclass
+ class Birthday:
+ name: str
+ birthday: datetime.date = field(kw_only=True)
+
+Here only ``birthday`` is keyword-only. If you set ``kw_only`` on
+individual fields, be aware that there are rules about re-ordering
+fields due to keyword-only fields needing to follow non-keyword-only
+fields. See the full dataclasses documentation for details.
+
+You can also specify that all fields following a KW_ONLY marker are
+keyword-only. This will probably be the most common usage:
+
+.. code-block:: python
+
+ from dataclasses import dataclass, KW_ONLY
+
+ @dataclass
+ class Point:
+ x: float
+ y: float
+ _: KW_ONLY
+ z: float = 0.0
+ t: float = 0.0
+
+Here, ``z`` and ``t`` are keyword-only parameters, while ``x`` and
+``y`` are not.
+(Contributed by Eric V. Smith in :issue:`43532`)
+
.. _distutils-deprecated:
distutils
More information about the Python-checkins
mailing list