Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a1ba359

Browse files
authored
Add What's New for dataclass keyword-only parameters. (GH-28158)
1 parent 936f6a1 commit a1ba359

1 file changed

Lines changed: 60 additions & 1 deletion

File tree

Doc/whatsnew/3.10.rst

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -983,9 +983,68 @@ they are provided by the underlying curses library.
983983
dataclasses
984984
-----------
985985
986-
Add ``slots`` parameter in :func:`dataclasses.dataclass` decorator.
986+
__slots__
987+
~~~~~~~~~
988+
989+
Added ``slots`` parameter in :func:`dataclasses.dataclass` decorator.
987990
(Contributed by Yurii Karabas in :issue:`42269`)
988991
992+
Keyword-only fields
993+
~~~~~~~~~~~~~~~~~~~
994+
995+
dataclassses now supports fields that are keyword-only in the
996+
generated __init__ method. There are a number of ways of specifying
997+
keyword-only fields.
998+
999+
You can say that every field is keyword-only:
1000+
1001+
.. code-block:: python
1002+
1003+
from dataclasses import dataclass
1004+
1005+
@dataclass(kw_only=True)
1006+
class Birthday:
1007+
name: str
1008+
birthday: datetime.date
1009+
1010+
Both ``name`` and ``birthday`` are keyword-only parameters to the
1011+
generated __init__ method.
1012+
1013+
You can specify keyword-only on a per-field basis:
1014+
1015+
.. code-block:: python
1016+
1017+
from dataclasses import dataclass
1018+
1019+
@dataclass
1020+
class Birthday:
1021+
name: str
1022+
birthday: datetime.date = field(kw_only=True)
1023+
1024+
Here only ``birthday`` is keyword-only. If you set ``kw_only`` on
1025+
individual fields, be aware that there are rules about re-ordering
1026+
fields due to keyword-only fields needing to follow non-keyword-only
1027+
fields. See the full dataclasses documentation for details.
1028+
1029+
You can also specify that all fields following a KW_ONLY marker are
1030+
keyword-only. This will probably be the most common usage:
1031+
1032+
.. code-block:: python
1033+
1034+
from dataclasses import dataclass, KW_ONLY
1035+
1036+
@dataclass
1037+
class Point:
1038+
x: float
1039+
y: float
1040+
_: KW_ONLY
1041+
z: float = 0.0
1042+
t: float = 0.0
1043+
1044+
Here, ``z`` and ``t`` are keyword-only parameters, while ``x`` and
1045+
``y`` are not.
1046+
(Contributed by Eric V. Smith in :issue:`43532`)
1047+
9891048
.. _distutils-deprecated:
9901049
9911050
distutils

0 commit comments

Comments
 (0)