12
12
--------------
13
13
14
14
This module provides a decorator and functions for automatically
15
- adding generated :term: `special method `\s such as :meth: `__init__ ` and
16
- :meth: `__repr__ ` to user-defined classes. It was originally described
15
+ adding generated :term: `special method `\s such as :meth: `~object. __init__ ` and
16
+ :meth: `~object. __repr__ ` to user-defined classes. It was originally described
17
17
in :pep: `557 `.
18
18
19
19
The member variables to use in these generated methods are defined
@@ -31,7 +31,7 @@ using :pep:`526` type annotations. For example, this code::
31
31
def total_cost(self) -> float:
32
32
return self.unit_price * self.quantity_on_hand
33
33
34
- will add, among other things, a :meth: `__init__ ` that looks like::
34
+ will add, among other things, a :meth: `~object. __init__ ` that looks like::
35
35
36
36
def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0):
37
37
self.name = name
@@ -86,105 +86,105 @@ Module contents
86
86
87
87
The parameters to :func: `dataclass ` are:
88
88
89
- - ``init ``: If true (the default), a :meth: `__init__ ` method will be
89
+ - ``init ``: If true (the default), a :meth: `~object. __init__ ` method will be
90
90
generated.
91
91
92
- If the class already defines :meth: `__init__ `, this parameter is
92
+ If the class already defines :meth: `~object. __init__ `, this parameter is
93
93
ignored.
94
94
95
- - ``repr ``: If true (the default), a :meth: `__repr__ ` method will be
95
+ - ``repr ``: If true (the default), a :meth: `~object. __repr__ ` method will be
96
96
generated. The generated repr string will have the class name and
97
97
the name and repr of each field, in the order they are defined in
98
98
the class. Fields that are marked as being excluded from the repr
99
99
are not included. For example:
100
100
``InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10) ``.
101
101
102
- If the class already defines :meth: `__repr__ `, this parameter is
102
+ If the class already defines :meth: `~object. __repr__ `, this parameter is
103
103
ignored.
104
104
105
- - ``eq ``: If true (the default), an :meth: `__eq__ ` method will be
105
+ - ``eq ``: If true (the default), an :meth: `~object. __eq__ ` method will be
106
106
generated. This method compares the class as if it were a tuple
107
107
of its fields, in order. Both instances in the comparison must
108
108
be of the identical type.
109
109
110
- If the class already defines :meth: `__eq__ `, this parameter is
110
+ If the class already defines :meth: `~object. __eq__ `, this parameter is
111
111
ignored.
112
112
113
- - ``order ``: If true (the default is ``False ``), :meth: `__lt__ `,
114
- :meth: `__le__ `, :meth: `__gt__ `, and :meth: `__ge__ ` methods will be
113
+ - ``order ``: If true (the default is ``False ``), :meth: `~object. __lt__ `,
114
+ :meth: `~object. __le__ `, :meth: `~object. __gt__ `, and :meth: `~object. __ge__ ` methods will be
115
115
generated. These compare the class as if it were a tuple of its
116
116
fields, in order. Both instances in the comparison must be of the
117
117
identical type. If ``order `` is true and ``eq `` is false, a
118
118
:exc: `ValueError ` is raised.
119
119
120
- If the class already defines any of :meth: `__lt__ `,
121
- :meth: `__le__ `, :meth: `__gt__ `, or :meth: `__ge__ `, then
120
+ If the class already defines any of :meth: `~object. __lt__ `,
121
+ :meth: `~object. __le__ `, :meth: `~object. __gt__ `, or :meth: `~object. __ge__ `, then
122
122
:exc: `TypeError ` is raised.
123
123
124
- - ``unsafe_hash ``: If ``False `` (the default), a :meth: `__hash__ ` method
124
+ - ``unsafe_hash ``: If ``False `` (the default), a :meth: `~object. __hash__ ` method
125
125
is generated according to how ``eq `` and ``frozen `` are set.
126
126
127
- :meth: `__hash__ ` is used by built-in :meth: `hash() `, and when objects are
127
+ :meth: `~object. __hash__ ` is used by built-in :meth: `hash() `, and when objects are
128
128
added to hashed collections such as dictionaries and sets. Having a
129
- :meth: `__hash__ ` implies that instances of the class are immutable.
129
+ :meth: `~object. __hash__ ` implies that instances of the class are immutable.
130
130
Mutability is a complicated property that depends on the programmer's
131
- intent, the existence and behavior of :meth: `__eq__ `, and the values of
131
+ intent, the existence and behavior of :meth: `~object. __eq__ `, and the values of
132
132
the ``eq `` and ``frozen `` flags in the :func: `dataclass ` decorator.
133
133
134
- By default, :func: `dataclass ` will not implicitly add a :meth: `__hash__ `
134
+ By default, :func: `dataclass ` will not implicitly add a :meth: `~object. __hash__ `
135
135
method unless it is safe to do so. Neither will it add or change an
136
- existing explicitly defined :meth: `__hash__ ` method. Setting the class
136
+ existing explicitly defined :meth: `~object. __hash__ ` method. Setting the class
137
137
attribute ``__hash__ = None `` has a specific meaning to Python, as
138
- described in the :meth: `__hash__ ` documentation.
138
+ described in the :meth: `~object. __hash__ ` documentation.
139
139
140
- If :meth: `__hash__ ` is not explicitly defined, or if it is set to ``None ``,
141
- then :func: `dataclass ` *may * add an implicit :meth: `__hash__ ` method.
140
+ If :meth: `~object. __hash__ ` is not explicitly defined, or if it is set to ``None ``,
141
+ then :func: `dataclass ` *may * add an implicit :meth: `~object. __hash__ ` method.
142
142
Although not recommended, you can force :func: `dataclass ` to create a
143
- :meth: `__hash__ ` method with ``unsafe_hash=True ``. This might be the case
143
+ :meth: `~object. __hash__ ` method with ``unsafe_hash=True ``. This might be the case
144
144
if your class is logically immutable but can nonetheless be mutated.
145
145
This is a specialized use case and should be considered carefully.
146
146
147
- Here are the rules governing implicit creation of a :meth: `__hash__ `
148
- method. Note that you cannot both have an explicit :meth: `__hash__ `
147
+ Here are the rules governing implicit creation of a :meth: `~object. __hash__ `
148
+ method. Note that you cannot both have an explicit :meth: `~object. __hash__ `
149
149
method in your dataclass and set ``unsafe_hash=True ``; this will result
150
150
in a :exc: `TypeError `.
151
151
152
152
If ``eq `` and ``frozen `` are both true, by default :func: `dataclass ` will
153
- generate a :meth: `__hash__ ` method for you. If ``eq `` is true and
154
- ``frozen `` is false, :meth: `__hash__ ` will be set to ``None ``, marking it
153
+ generate a :meth: `~object. __hash__ ` method for you. If ``eq `` is true and
154
+ ``frozen `` is false, :meth: `~object. __hash__ ` will be set to ``None ``, marking it
155
155
unhashable (which it is, since it is mutable). If ``eq `` is false,
156
- :meth: `__hash__ ` will be left untouched meaning the :meth: `__hash__ `
156
+ :meth: `~object. __hash__ ` will be left untouched meaning the :meth: `~object. __hash__ `
157
157
method of the superclass will be used (if the superclass is
158
158
:class: `object `, this means it will fall back to id-based hashing).
159
159
160
160
- ``frozen ``: If true (the default is ``False ``), assigning to fields will
161
161
generate an exception. This emulates read-only frozen instances. If
162
- :meth: `__setattr__ ` or :meth: `__delattr__ ` is defined in the class, then
162
+ :meth: `~object. __setattr__ ` or :meth: `~object. __delattr__ ` is defined in the class, then
163
163
:exc: `TypeError ` is raised. See the discussion below.
164
164
165
165
- ``match_args ``: If true (the default is ``True ``), the
166
166
``__match_args__ `` tuple will be created from the list of
167
- parameters to the generated :meth: `__init__ ` method (even if
168
- :meth: `__init__ ` is not generated, see above). If false, or if
167
+ parameters to the generated :meth: `~object. __init__ ` method (even if
168
+ :meth: `~object. __init__ ` is not generated, see above). If false, or if
169
169
``__match_args__ `` is already defined in the class, then
170
170
``__match_args__ `` will not be generated.
171
171
172
172
.. versionadded :: 3.10
173
173
174
174
- ``kw_only ``: If true (the default value is ``False ``), then all
175
175
fields will be marked as keyword-only. If a field is marked as
176
- keyword-only, then the only effect is that the :meth: `__init__ `
176
+ keyword-only, then the only effect is that the :meth: `~object. __init__ `
177
177
parameter generated from a keyword-only field must be specified
178
- with a keyword when :meth: `__init__ ` is called. There is no
178
+ with a keyword when :meth: `~object. __init__ ` is called. There is no
179
179
effect on any other aspect of dataclasses. See the
180
180
:term: `parameter ` glossary entry for details. Also see the
181
181
:const: `KW_ONLY ` section.
182
182
183
183
.. versionadded :: 3.10
184
184
185
- - ``slots ``: If true (the default is ``False ``), :attr: `__slots__ ` attribute
185
+ - ``slots ``: If true (the default is ``False ``), :attr: `~object. __slots__ ` attribute
186
186
will be generated and new class will be returned instead of the original one.
187
- If :attr: `__slots__ ` is already defined in the class, then :exc: `TypeError `
187
+ If :attr: `~object. __slots__ ` is already defined in the class, then :exc: `TypeError `
188
188
is raised.
189
189
190
190
.. versionadded :: 3.10
@@ -215,7 +215,7 @@ Module contents
215
215
b: int = 0 # assign a default value for 'b'
216
216
217
217
In this example, both ``a `` and ``b `` will be included in the added
218
- :meth: `__init__ ` method, which will be defined as::
218
+ :meth: `~object. __init__ ` method, which will be defined as::
219
219
220
220
def __init__(self, a: int, b: int = 0):
221
221
@@ -256,13 +256,13 @@ Module contents
256
256
error to specify both ``default `` and ``default_factory ``.
257
257
258
258
- ``init ``: If true (the default), this field is included as a
259
- parameter to the generated :meth: `__init__ ` method.
259
+ parameter to the generated :meth: `~object. __init__ ` method.
260
260
261
261
- ``repr ``: If true (the default), this field is included in the
262
- string returned by the generated :meth: `__repr__ ` method.
262
+ string returned by the generated :meth: `~object. __repr__ ` method.
263
263
264
264
- ``hash ``: This can be a bool or ``None ``. If true, this field is
265
- included in the generated :meth: `__hash__ ` method. If ``None `` (the
265
+ included in the generated :meth: `~object. __hash__ ` method. If ``None `` (the
266
266
default), use the value of ``compare ``: this would normally be
267
267
the expected behavior. A field should be considered in the hash
268
268
if it's used for comparisons. Setting this value to anything
@@ -275,8 +275,8 @@ Module contents
275
275
is excluded from the hash, it will still be used for comparisons.
276
276
277
277
- ``compare ``: If true (the default), this field is included in the
278
- generated equality and comparison methods (:meth: `__eq__ `,
279
- :meth: `__gt__ `, et al.).
278
+ generated equality and comparison methods (:meth: `~object. __eq__ `,
279
+ :meth: `~object. __gt__ `, et al.).
280
280
281
281
- ``metadata ``: This can be a mapping or None. None is treated as
282
282
an empty dict. This value is wrapped in
@@ -287,7 +287,7 @@ Module contents
287
287
namespace in the metadata.
288
288
289
289
- ``kw_only ``: If true, this field will be marked as keyword-only.
290
- This is used when the generated :meth: `__init__ ` method's
290
+ This is used when the generated :meth: `~object. __init__ ` method's
291
291
parameters are computed.
292
292
293
293
.. versionadded :: 3.10
@@ -435,21 +435,21 @@ Module contents
435
435
Class, raises :exc: `TypeError `. If values in ``changes `` do not
436
436
specify fields, raises :exc: `TypeError `.
437
437
438
- The newly returned object is created by calling the :meth: `__init__ `
438
+ The newly returned object is created by calling the :meth: `~object. __init__ `
439
439
method of the dataclass. This ensures that
440
- :meth : `__post_init__ `, if present, is also called.
440
+ :ref : `__post_init__ < post-init-processing > `, if present, is also called.
441
441
442
442
Init-only variables without default values, if any exist, must be
443
443
specified on the call to :func: `replace ` so that they can be passed to
444
- :meth: `__init__ ` and :meth : `__post_init__ `.
444
+ :meth: `~object. __init__ ` and :ref : `__post_init__ < post-init-processing > `.
445
445
446
446
It is an error for ``changes `` to contain any fields that are
447
447
defined as having ``init=False ``. A :exc: `ValueError ` will be raised
448
448
in this case.
449
449
450
450
Be forewarned about how ``init=False `` fields work during a call to
451
451
:func: `replace `. They are not copied from the source object, but
452
- rather are initialized in :meth : `__post_init__ `, if they're
452
+ rather are initialized in :ref : `__post_init__ < post-init-processing > `, if they're
453
453
initialized at all. It is expected that ``init=False `` fields will
454
454
be rarely and judiciously used. If they are used, it might be wise
455
455
to have alternate class constructors, or perhaps a custom
@@ -480,7 +480,7 @@ Module contents
480
480
:const: `KW_ONLY ` is otherwise completely ignored. This includes the
481
481
name of such a field. By convention, a name of ``_ `` is used for a
482
482
:const: `KW_ONLY ` field. Keyword-only fields signify
483
- :meth: `__init__ ` parameters that must be specified as keywords when
483
+ :meth: `~object. __init__ ` parameters that must be specified as keywords when
484
484
the class is instantiated.
485
485
486
486
In this example, the fields ``y `` and ``z `` will be marked as keyword-only fields::
@@ -501,20 +501,22 @@ Module contents
501
501
502
502
.. exception :: FrozenInstanceError
503
503
504
- Raised when an implicitly defined :meth: `__setattr__ ` or
505
- :meth: `__delattr__ ` is called on a dataclass which was defined with
504
+ Raised when an implicitly defined :meth: `~object. __setattr__ ` or
505
+ :meth: `~object. __delattr__ ` is called on a dataclass which was defined with
506
506
``frozen=True ``. It is a subclass of :exc: `AttributeError `.
507
507
508
+ .. _post-init-processing :
509
+
508
510
Post-init processing
509
511
--------------------
510
512
511
- The generated :meth: `__init__ ` code will call a method named
512
- :meth: `__post_init__ `, if :meth: `__post_init__ ` is defined on the
513
+ The generated :meth: `~object. __init__ ` code will call a method named
514
+ :meth: `! __post_init__ `, if :meth: `! __post_init__ ` is defined on the
513
515
class. It will normally be called as ``self.__post_init__() ``.
514
516
However, if any ``InitVar `` fields are defined, they will also be
515
- passed to :meth: `__post_init__ ` in the order they were defined in the
516
- class. If no :meth: `__init__ ` method is generated, then
517
- :meth: `__post_init__ ` will not automatically be called.
517
+ passed to :meth: `! __post_init__ ` in the order they were defined in the
518
+ class. If no :meth: `~object. __init__ ` method is generated, then
519
+ :meth: `! __post_init__ ` will not automatically be called.
518
520
519
521
Among other uses, this allows for initializing field values that
520
522
depend on one or more other fields. For example::
@@ -528,10 +530,10 @@ depend on one or more other fields. For example::
528
530
def __post_init__(self):
529
531
self.c = self.a + self.b
530
532
531
- The :meth: `__init__ ` method generated by :func: `dataclass ` does not call base
532
- class :meth: `__init__ ` methods. If the base class has an :meth: `__init__ ` method
533
+ The :meth: `~object. __init__ ` method generated by :func: `dataclass ` does not call base
534
+ class :meth: `~object. __init__ ` methods. If the base class has an :meth: `~object. __init__ ` method
533
535
that has to be called, it is common to call this method in a
534
- :meth: `__post_init__ ` method::
536
+ :meth: `! __post_init__ ` method::
535
537
536
538
@dataclass
537
539
class Rectangle:
@@ -545,12 +547,12 @@ that has to be called, it is common to call this method in a
545
547
def __post_init__(self):
546
548
super().__init__(self.side, self.side)
547
549
548
- Note, however, that in general the dataclass-generated :meth: `__init__ ` methods
550
+ Note, however, that in general the dataclass-generated :meth: `~object. __init__ ` methods
549
551
don't need to be called, since the derived dataclass will take care of
550
552
initializing all fields of any base class that is a dataclass itself.
551
553
552
554
See the section below on init-only variables for ways to pass
553
- parameters to :meth: `__post_init__ `. Also see the warning about how
555
+ parameters to :meth: `! __post_init__ `. Also see the warning about how
554
556
:func: `replace ` handles ``init=False `` fields.
555
557
556
558
Class variables
@@ -573,8 +575,8 @@ if the type of a field is of type ``dataclasses.InitVar``. If a field
573
575
is an ``InitVar ``, it is considered a pseudo-field called an init-only
574
576
field. As it is not a true field, it is not returned by the
575
577
module-level :func: `fields ` function. Init-only fields are added as
576
- parameters to the generated :meth: `__init__ ` method, and are passed to
577
- the optional :meth : `__post_init__ ` method. They are not otherwise used
578
+ parameters to the generated :meth: `~object. __init__ ` method, and are passed to
579
+ the optional :ref : `__post_init__ < post-init-processing > ` method. They are not otherwise used
578
580
by dataclasses.
579
581
580
582
For example, suppose a field will be initialized from a database, if a
@@ -601,12 +603,12 @@ Frozen instances
601
603
It is not possible to create truly immutable Python objects. However,
602
604
by passing ``frozen=True `` to the :meth: `dataclass ` decorator you can
603
605
emulate immutability. In that case, dataclasses will add
604
- :meth: `__setattr__ ` and :meth: `__delattr__ ` methods to the class. These
606
+ :meth: `~object. __setattr__ ` and :meth: `~object. __delattr__ ` methods to the class. These
605
607
methods will raise a :exc: `FrozenInstanceError ` when invoked.
606
608
607
609
There is a tiny performance penalty when using ``frozen=True ``:
608
- :meth: `__init__ ` cannot use simple assignment to initialize fields, and
609
- must use :meth: `object.__setattr__ `.
610
+ :meth: `~object. __init__ ` cannot use simple assignment to initialize fields, and
611
+ must use :meth: `~ object.__setattr__ `.
610
612
611
613
Inheritance
612
614
-----------
@@ -634,14 +636,14 @@ example::
634
636
The final list of fields is, in order, ``x ``, ``y ``, ``z ``. The final
635
637
type of ``x `` is ``int ``, as specified in class ``C ``.
636
638
637
- The generated :meth: `__init__ ` method for ``C `` will look like::
639
+ The generated :meth: `~object. __init__ ` method for ``C `` will look like::
638
640
639
641
def __init__(self, x: int = 15, y: int = 0, z: int = 10):
640
642
641
- Re-ordering of keyword-only parameters in :meth: `__init__ `
642
- ----------------------------------------------------------
643
+ Re-ordering of keyword-only parameters in :meth: `~object. __init__ `
644
+ ------------------------------------------------------------------
643
645
644
- After the parameters needed for :meth: `__init__ ` are computed, any
646
+ After the parameters needed for :meth: `~object. __init__ ` are computed, any
645
647
keyword-only parameters are moved to come after all regular
646
648
(non-keyword-only) parameters. This is a requirement of how
647
649
keyword-only parameters are implemented in Python: they must come
@@ -662,7 +664,7 @@ fields, and ``Base.x`` and ``D.z`` are regular fields::
662
664
z: int = 10
663
665
t: int = field(kw_only=True, default=0)
664
666
665
- The generated :meth: `__init__ ` method for ``D `` will look like::
667
+ The generated :meth: `~object. __init__ ` method for ``D `` will look like::
666
668
667
669
def __init__(self, x: Any = 15.0, z: int = 10, *, y: int = 0, w: int = 1, t: int = 0):
668
670
@@ -671,7 +673,7 @@ the list of fields: parameters derived from regular fields are
671
673
followed by parameters derived from keyword-only fields.
672
674
673
675
The relative ordering of keyword-only parameters is maintained in the
674
- re-ordered :meth: `__init__ ` parameter list.
676
+ re-ordered :meth: `~object. __init__ ` parameter list.
675
677
676
678
677
679
Default factory functions
@@ -683,10 +685,10 @@ example, to create a new instance of a list, use::
683
685
684
686
mylist: list = field(default_factory=list)
685
687
686
- If a field is excluded from :meth: `__init__ ` (using ``init=False ``)
688
+ If a field is excluded from :meth: `~object. __init__ ` (using ``init=False ``)
687
689
and the field also specifies ``default_factory ``, then the default
688
690
factory function will always be called from the generated
689
- :meth: `__init__ ` function. This happens because there is no other
691
+ :meth: `~object. __init__ ` function. This happens because there is no other
690
692
way to give the field an initial value.
691
693
692
694
Mutable default values
0 commit comments