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
@@ -431,21 +431,21 @@ Module contents
431
431
Class, raises :exc: `TypeError `. If values in ``changes `` do not
432
432
specify fields, raises :exc: `TypeError `.
433
433
434
- The newly returned object is created by calling the :meth: `__init__ `
434
+ The newly returned object is created by calling the :meth: `~object. __init__ `
435
435
method of the dataclass. This ensures that
436
- :meth : `__post_init__ `, if present, is also called.
436
+ :ref : `__post_init__ < post-init-processing > `, if present, is also called.
437
437
438
438
Init-only variables without default values, if any exist, must be
439
439
specified on the call to :func: `replace ` so that they can be passed to
440
- :meth: `__init__ ` and :meth : `__post_init__ `.
440
+ :meth: `~object. __init__ ` and :ref : `__post_init__ < post-init-processing > `.
441
441
442
442
It is an error for ``changes `` to contain any fields that are
443
443
defined as having ``init=False ``. A :exc: `ValueError ` will be raised
444
444
in this case.
445
445
446
446
Be forewarned about how ``init=False `` fields work during a call to
447
447
:func: `replace `. They are not copied from the source object, but
448
- rather are initialized in :meth : `__post_init__ `, if they're
448
+ rather are initialized in :ref : `__post_init__ < post-init-processing > `, if they're
449
449
initialized at all. It is expected that ``init=False `` fields will
450
450
be rarely and judiciously used. If they are used, it might be wise
451
451
to have alternate class constructors, or perhaps a custom
@@ -476,7 +476,7 @@ Module contents
476
476
:const: `KW_ONLY ` is otherwise completely ignored. This includes the
477
477
name of such a field. By convention, a name of ``_ `` is used for a
478
478
:const: `KW_ONLY ` field. Keyword-only fields signify
479
- :meth: `__init__ ` parameters that must be specified as keywords when
479
+ :meth: `~object. __init__ ` parameters that must be specified as keywords when
480
480
the class is instantiated.
481
481
482
482
In this example, the fields ``y `` and ``z `` will be marked as keyword-only fields::
@@ -497,20 +497,22 @@ Module contents
497
497
498
498
.. exception :: FrozenInstanceError
499
499
500
- Raised when an implicitly defined :meth: `__setattr__ ` or
501
- :meth: `__delattr__ ` is called on a dataclass which was defined with
500
+ Raised when an implicitly defined :meth: `~object. __setattr__ ` or
501
+ :meth: `~object. __delattr__ ` is called on a dataclass which was defined with
502
502
``frozen=True ``. It is a subclass of :exc: `AttributeError `.
503
503
504
+ .. _post-init-processing :
505
+
504
506
Post-init processing
505
507
--------------------
506
508
507
- The generated :meth: `__init__ ` code will call a method named
508
- :meth: `__post_init__ `, if :meth: `__post_init__ ` is defined on the
509
+ The generated :meth: `~object. __init__ ` code will call a method named
510
+ :meth: `! __post_init__ `, if :meth: `! __post_init__ ` is defined on the
509
511
class. It will normally be called as ``self.__post_init__() ``.
510
512
However, if any ``InitVar `` fields are defined, they will also be
511
- passed to :meth: `__post_init__ ` in the order they were defined in the
512
- class. If no :meth: `__init__ ` method is generated, then
513
- :meth: `__post_init__ ` will not automatically be called.
513
+ passed to :meth: `! __post_init__ ` in the order they were defined in the
514
+ class. If no :meth: `~object. __init__ ` method is generated, then
515
+ :meth: `! __post_init__ ` will not automatically be called.
514
516
515
517
Among other uses, this allows for initializing field values that
516
518
depend on one or more other fields. For example::
@@ -524,10 +526,10 @@ depend on one or more other fields. For example::
524
526
def __post_init__(self):
525
527
self.c = self.a + self.b
526
528
527
- The :meth: `__init__ ` method generated by :func: `dataclass ` does not call base
528
- class :meth: `__init__ ` methods. If the base class has an :meth: `__init__ ` method
529
+ The :meth: `~object. __init__ ` method generated by :func: `dataclass ` does not call base
530
+ class :meth: `~object. __init__ ` methods. If the base class has an :meth: `~object. __init__ ` method
529
531
that has to be called, it is common to call this method in a
530
- :meth: `__post_init__ ` method::
532
+ :meth: `! __post_init__ ` method::
531
533
532
534
@dataclass
533
535
class Rectangle:
@@ -541,12 +543,12 @@ that has to be called, it is common to call this method in a
541
543
def __post_init__(self):
542
544
super().__init__(self.side, self.side)
543
545
544
- Note, however, that in general the dataclass-generated :meth: `__init__ ` methods
546
+ Note, however, that in general the dataclass-generated :meth: `~object. __init__ ` methods
545
547
don't need to be called, since the derived dataclass will take care of
546
548
initializing all fields of any base class that is a dataclass itself.
547
549
548
550
See the section below on init-only variables for ways to pass
549
- parameters to :meth: `__post_init__ `. Also see the warning about how
551
+ parameters to :meth: `! __post_init__ `. Also see the warning about how
550
552
:func: `replace ` handles ``init=False `` fields.
551
553
552
554
Class variables
@@ -569,8 +571,8 @@ if the type of a field is of type ``dataclasses.InitVar``. If a field
569
571
is an ``InitVar ``, it is considered a pseudo-field called an init-only
570
572
field. As it is not a true field, it is not returned by the
571
573
module-level :func: `fields ` function. Init-only fields are added as
572
- parameters to the generated :meth: `__init__ ` method, and are passed to
573
- the optional :meth : `__post_init__ ` method. They are not otherwise used
574
+ parameters to the generated :meth: `~object. __init__ ` method, and are passed to
575
+ the optional :ref : `__post_init__ < post-init-processing > ` method. They are not otherwise used
574
576
by dataclasses.
575
577
576
578
For example, suppose a field will be initialized from a database, if a
@@ -597,12 +599,12 @@ Frozen instances
597
599
It is not possible to create truly immutable Python objects. However,
598
600
by passing ``frozen=True `` to the :meth: `dataclass ` decorator you can
599
601
emulate immutability. In that case, dataclasses will add
600
- :meth: `__setattr__ ` and :meth: `__delattr__ ` methods to the class. These
602
+ :meth: `~object. __setattr__ ` and :meth: `~object. __delattr__ ` methods to the class. These
601
603
methods will raise a :exc: `FrozenInstanceError ` when invoked.
602
604
603
605
There is a tiny performance penalty when using ``frozen=True ``:
604
- :meth: `__init__ ` cannot use simple assignment to initialize fields, and
605
- must use :meth: `object.__setattr__ `.
606
+ :meth: `~object. __init__ ` cannot use simple assignment to initialize fields, and
607
+ must use :meth: `~ object.__setattr__ `.
606
608
607
609
Inheritance
608
610
-----------
@@ -630,14 +632,14 @@ example::
630
632
The final list of fields is, in order, ``x ``, ``y ``, ``z ``. The final
631
633
type of ``x `` is ``int ``, as specified in class ``C ``.
632
634
633
- The generated :meth: `__init__ ` method for ``C `` will look like::
635
+ The generated :meth: `~object. __init__ ` method for ``C `` will look like::
634
636
635
637
def __init__(self, x: int = 15, y: int = 0, z: int = 10):
636
638
637
- Re-ordering of keyword-only parameters in :meth: `__init__ `
638
- ----------------------------------------------------------
639
+ Re-ordering of keyword-only parameters in :meth: `~object. __init__ `
640
+ ------------------------------------------------------------------
639
641
640
- After the parameters needed for :meth: `__init__ ` are computed, any
642
+ After the parameters needed for :meth: `~object. __init__ ` are computed, any
641
643
keyword-only parameters are moved to come after all regular
642
644
(non-keyword-only) parameters. This is a requirement of how
643
645
keyword-only parameters are implemented in Python: they must come
@@ -658,7 +660,7 @@ fields, and ``Base.x`` and ``D.z`` are regular fields::
658
660
z: int = 10
659
661
t: int = field(kw_only=True, default=0)
660
662
661
- The generated :meth: `__init__ ` method for ``D `` will look like::
663
+ The generated :meth: `~object. __init__ ` method for ``D `` will look like::
662
664
663
665
def __init__(self, x: Any = 15.0, z: int = 10, *, y: int = 0, w: int = 1, t: int = 0):
664
666
@@ -667,7 +669,7 @@ the list of fields: parameters derived from regular fields are
667
669
followed by parameters derived from keyword-only fields.
668
670
669
671
The relative ordering of keyword-only parameters is maintained in the
670
- re-ordered :meth: `__init__ ` parameter list.
672
+ re-ordered :meth: `~object. __init__ ` parameter list.
671
673
672
674
673
675
Default factory functions
@@ -679,10 +681,10 @@ example, to create a new instance of a list, use::
679
681
680
682
mylist: list = field(default_factory=list)
681
683
682
- If a field is excluded from :meth: `__init__ ` (using ``init=False ``)
684
+ If a field is excluded from :meth: `~object. __init__ ` (using ``init=False ``)
683
685
and the field also specifies ``default_factory ``, then the default
684
686
factory function will always be called from the generated
685
- :meth: `__init__ ` function. This happens because there is no other
687
+ :meth: `~object. __init__ ` function. This happens because there is no other
686
688
way to give the field an initial value.
687
689
688
690
Mutable default values
0 commit comments