Debian Codegraph @

Doc/library/dataclasses.rst

raw
1 :mod:`!dataclasses` --- Data Classes
2 ====================================
3
4 .. module:: dataclasses
5 :synopsis: Generate special methods on user-defined classes.
6
7 .. moduleauthor:: Eric V. Smith <[email protected]>
8 .. sectionauthor:: Eric V. Smith <[email protected]>
9
10 **Source code:** :source:`Lib/dataclasses.py`
11
12 --------------
13
14 This module provides a decorator and functions for automatically
15 adding generated :term:`special methods <special method>` such as :meth:`~object.__init__` and
16 :meth:`~object.__repr__` to user-defined classes. It was originally described
17 in :pep:`557`.
18
19 The member variables to use in these generated methods are defined
20 using :pep:`526` type annotations. For example, this code::
21
22 from dataclasses import dataclass
23
24 @dataclass
25 class InventoryItem:
26 """Class for keeping track of an item in inventory."""
27 name: str
28 unit_price: float
29 quantity_on_hand: int = 0
30
31 def total_cost(self) -> float:
32 return self.unit_price * self.quantity_on_hand
33
34 will add, among other things, a :meth:`!__init__` that looks like::
35
36 def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0):
37 self.name = name
38 self.unit_price = unit_price
39 self.quantity_on_hand = quantity_on_hand
40
41 Note that this method is automatically added to the class: it is not
42 directly specified in the :class:`!InventoryItem` definition shown above.
43
44 .. versionadded:: 3.7
45
46 Module contents
47 ---------------
48
49 .. decorator:: dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False)
50
51 This function is a :term:`decorator` that is used to add generated
52 :term:`special methods <special method>` to classes, as described below.
53
54 The ``@dataclass`` decorator examines the class to find
55 ``field``\s. A ``field`` is defined as a class variable that has a
56 :term:`type annotation <variable annotation>`. With two
57 exceptions described below, nothing in ``@dataclass``
58 examines the type specified in the variable annotation.
59
60 The order of the fields in all of the generated methods is the
61 order in which they appear in the class definition.
62
63 The ``@dataclass`` decorator will add various "dunder" methods to
64 the class, described below. If any of the added methods already
65 exist in the class, the behavior depends on the parameter, as documented
66 below. The decorator returns the same class that it is called on; no new
67 class is created.
68
69 If ``@dataclass`` is used just as a simple decorator with no parameters,
70 it acts as if it has the default values documented in this
71 signature. That is, these three uses of ``@dataclass`` are
72 equivalent::
73
74 @dataclass
75 class C:
76 ...
77
78 @dataclass()
79 class C:
80 ...
81
82 @dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False,
83 match_args=True, kw_only=False, slots=False, weakref_slot=False)
84 class C:
85 ...
86
87 The parameters to ``@dataclass`` are:
88
89 - *init*: If true (the default), a :meth:`~object.__init__` method will be
90 generated.
91
92 If the class already defines :meth:`!__init__`, this parameter is
93 ignored.
94
95 - *repr*: If true (the default), a :meth:`~object.__repr__` method will be
96 generated. The generated repr string will have the class name and
97 the name and repr of each field, in the order they are defined in
98 the class. Fields that are marked as being excluded from the repr
99 are not included. For example:
100 ``InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10)``.
101
102 If the class already defines :meth:`!__repr__`, this parameter is
103 ignored.
104
105 - *eq*: If true (the default), an :meth:`~object.__eq__` method will be
106 generated.
107
108 This method compares the class by comparing each field in order. Both
109 instances in the comparison must be of the identical type.
110
111 If the class already defines :meth:`!__eq__`, this parameter is ignored.
112
113 .. versionchanged:: 3.13
114 The generated ``__eq__`` method now compares each field individually
115 (for example, ``self.a == other.a and self.b == other.b``), rather than
116 comparing tuples of fields as in previous versions.
117
118 This change makes the comparison faster but it may alter results in cases
119 where attributes compare equal by identity but not by value (such as
120 ``float('nan')``).
121
122 In Python 3.12 and earlier, the comparison was performed by creating
123 tuples of the fields and comparing them (for example,
124 ``(self.a, self.b) == (other.a, other.b)``).
125
126 - *order*: If true (the default is ``False``), :meth:`~object.__lt__`,
127 :meth:`~object.__le__`, :meth:`~object.__gt__`, and :meth:`~object.__ge__` methods will be
128 generated. These compare the class as if it were a tuple of its
129 fields, in order. Both instances in the comparison must be of the
130 identical type. If *order* is true and *eq* is false, a
131 :exc:`ValueError` is raised.
132
133 If the class already defines any of :meth:`!__lt__`,
134 :meth:`!__le__`, :meth:`!__gt__`, or :meth:`!__ge__`, then
135 :exc:`TypeError` is raised.
136
137 - *unsafe_hash*: If true, force ``dataclasses`` to create a
138 :meth:`~object.__hash__` method, even though it may not be safe to do so.
139 Otherwise, generate a :meth:`~object.__hash__` method according to how
140 *eq* and *frozen* are set.
141 The default value is ``False``.
142
143 :meth:`!__hash__` is used by built-in :meth:`hash`, and when objects are
144 added to hashed collections such as dictionaries and sets. Having a
145 :meth:`!__hash__` implies that instances of the class are immutable.
146 Mutability is a complicated property that depends on the programmer's
147 intent, the existence and behavior of :meth:`!__eq__`, and the values of
148 the *eq* and *frozen* flags in the ``@dataclass`` decorator.
149
150 By default, ``@dataclass`` will not implicitly add a :meth:`~object.__hash__`
151 method unless it is safe to do so. Neither will it add or change an
152 existing explicitly defined :meth:`!__hash__` method. Setting the class
153 attribute ``__hash__ = None`` has a specific meaning to Python, as
154 described in the :meth:`!__hash__` documentation.
155
156 If :meth:`!__hash__` is not explicitly defined, or if it is set to ``None``,
157 then ``@dataclass`` *may* add an implicit :meth:`!__hash__` method.
158 Although not recommended, you can force ``@dataclass`` to create a
159 :meth:`!__hash__` method with ``unsafe_hash=True``. This might be the case
160 if your class is logically immutable but can still be mutated.
161 This is a specialized use case and should be considered carefully.
162
163 Here are the rules governing implicit creation of a :meth:`!__hash__`
164 method. Note that you cannot both have an explicit :meth:`!__hash__`
165 method in your dataclass and set ``unsafe_hash=True``; this will result
166 in a :exc:`TypeError`.
167
168 If *eq* and *frozen* are both true, by default ``@dataclass`` will
169 generate a :meth:`!__hash__` method for you. If *eq* is true and
170 *frozen* is false, :meth:`!__hash__` will be set to ``None``, marking it
171 unhashable (which it is, since it is mutable). If *eq* is false,
172 :meth:`!__hash__` will be left untouched meaning the :meth:`!__hash__`
173 method of the superclass will be used (if the superclass is
174 :class:`object`, this means it will fall back to id-based hashing).
175
176 - *frozen*: If true (the default is ``False``), assigning to fields will
177 generate an exception. This emulates read-only frozen instances.
178 See the :ref:`discussion <dataclasses-frozen>` below.
179
180 If :meth:`~object.__setattr__` or :meth:`~object.__delattr__` is defined in the class
181 and *frozen* is true, then :exc:`TypeError` is raised.
182
183 - *match_args*: If true (the default is ``True``), the
184 :attr:`~object.__match_args__` tuple will be created from the list of
185 non keyword-only parameters to the generated :meth:`~object.__init__` method (even if
186 :meth:`!__init__` is not generated, see above). If false, or if
187 :attr:`!__match_args__` is already defined in the class, then
188 :attr:`!__match_args__` will not be generated.
189
190 .. versionadded:: 3.10
191
192 - *kw_only*: If true (the default value is ``False``), then all
193 fields will be marked as keyword-only. If a field is marked as
194 keyword-only, then the only effect is that the :meth:`~object.__init__`
195 parameter generated from a keyword-only field must be specified
196 with a keyword when :meth:`!__init__` is called. See the :term:`parameter`
197 glossary entry for details. Also see the
198 :const:`KW_ONLY` section.
199
200 Keyword-only fields are not included in :attr:`!__match_args__`.
201
202 .. versionadded:: 3.10
203
204 - *slots*: If true (the default is ``False``), :attr:`~object.__slots__` attribute
205 will be generated and new class will be returned instead of the original one.
206 If :attr:`!__slots__` is already defined in the class, then :exc:`TypeError`
207 is raised.
208
209 .. warning::
210 Calling no-arg :func:`super` in dataclasses using ``slots=True``
211 will result in the following exception being raised:
212 ``TypeError: super(type, obj): obj must be an instance or subtype of type``.
213 The two-arg :func:`super` is a valid workaround.
214 See :gh:`90562` for full details.
215
216 .. warning::
217 Passing parameters to a base class :meth:`~object.__init_subclass__`
218 when using ``slots=True`` will result in a :exc:`TypeError`.
219 Either use ``__init_subclass__`` with no parameters
220 or use default values as a workaround.
221 See :gh:`91126` for full details.
222
223 .. versionadded:: 3.10
224
225 .. versionchanged:: 3.11
226 If a field name is already included in the :attr:`!__slots__`
227 of a base class, it will not be included in the generated :attr:`!__slots__`
228 to prevent :ref:`overriding them <datamodel-note-slots>`.
229 Therefore, do not use :attr:`!__slots__` to retrieve the field names of a
230 dataclass. Use :func:`fields` instead.
231 To be able to determine inherited slots,
232 base class :attr:`!__slots__` may be any iterable, but *not* an iterator.
233
234
235 - *weakref_slot*: If true (the default is ``False``), add a slot
236 named "__weakref__", which is required to make an instance
237 :func:`weakref-able <weakref.ref>`.
238 It is an error to specify ``weakref_slot=True``
239 without also specifying ``slots=True``.
240
241 .. versionadded:: 3.11
242
243 ``field``\s may optionally specify a default value, using normal
244 Python syntax::
245
246 @dataclass
247 class C:
248 a: int # 'a' has no default value
249 b: int = 0 # assign a default value for 'b'
250
251 In this example, both :attr:`!a` and :attr:`!b` will be included in the added
252 :meth:`~object.__init__` method, which will be defined as::
253
254 def __init__(self, a: int, b: int = 0):
255
256 :exc:`TypeError` will be raised if a field without a default value
257 follows a field with a default value. This is true whether this
258 occurs in a single class, or as a result of class inheritance.
259
260 .. function:: field(*, default=MISSING, default_factory=MISSING, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=MISSING)
261
262 For common and simple use cases, no other functionality is
263 required. There are, however, some dataclass features that
264 require additional per-field information. To satisfy this need for
265 additional information, you can replace the default field value
266 with a call to the provided :func:`!field` function. For example::
267
268 @dataclass
269 class C:
270 mylist: list[int] = field(default_factory=list)
271
272 c = C()
273 c.mylist += [1, 2, 3]
274
275 As shown above, the :const:`MISSING` value is a sentinel object used to
276 detect if some parameters are provided by the user. This sentinel is
277 used because ``None`` is a valid value for some parameters with
278 a distinct meaning. No code should directly use the :const:`MISSING` value.
279
280 The parameters to :func:`!field` are:
281
282 - *default*: If provided, this will be the default value for this
283 field. This is needed because the :func:`!field` call itself
284 replaces the normal position of the default value.
285
286 - *default_factory*: If provided, it must be a zero-argument
287 callable that will be called when a default value is needed for
288 this field. Among other purposes, this can be used to specify
289 fields with mutable default values, as discussed below. It is an
290 error to specify both *default* and *default_factory*.
291
292 - *init*: If true (the default), this field is included as a
293 parameter to the generated :meth:`~object.__init__` method.
294
295 - *repr*: If true (the default), this field is included in the
296 string returned by the generated :meth:`~object.__repr__` method.
297
298 - *hash*: This can be a bool or ``None``. If true, this field is
299 included in the generated :meth:`~object.__hash__` method. If false,
300 this field is excluded from the generated :meth:`~object.__hash__`.
301 If ``None`` (the default), use the value of *compare*: this would
302 normally be the expected behavior, since a field should be included
303 in the hash if it's used for comparisons. Setting this value to anything
304 other than ``None`` is discouraged.
305
306 One possible reason to set ``hash=False`` but ``compare=True``
307 would be if a field is expensive to compute a hash value for,
308 that field is needed for equality testing, and there are other
309 fields that contribute to the type's hash value. Even if a field
310 is excluded from the hash, it will still be used for comparisons.
311
312 - *compare*: If true (the default), this field is included in the
313 generated equality and comparison methods (:meth:`~object.__eq__`,
314 :meth:`~object.__gt__`, et al.).
315
316 - *metadata*: This can be a mapping or ``None``. ``None`` is treated as
317 an empty dict. This value is wrapped in
318 :func:`~types.MappingProxyType` to make it read-only, and exposed
319 on the :class:`Field` object. It is not used at all by Data
320 Classes, and is provided as a third-party extension mechanism.
321 Multiple third-parties can each have their own key, to use as a
322 namespace in the metadata.
323
324 - *kw_only*: If true, this field will be marked as keyword-only.
325 This is used when the generated :meth:`~object.__init__` method's
326 parameters are computed.
327
328 Keyword-only fields are also not included in :attr:`!__match_args__`.
329
330 .. versionadded:: 3.10
331
332 If the default value of a field is specified by a call to
333 :func:`!field`, then the class attribute for this field will be
334 replaced by the specified *default* value. If *default* is not
335 provided, then the class attribute will be deleted. The intent is
336 that after the :deco:`dataclass` decorator runs, the class
337 attributes will all contain the default values for the fields, just
338 as if the default value itself were specified. For example,
339 after::
340
341 @dataclass
342 class C:
343 x: int
344 y: int = field(repr=False)
345 z: int = field(repr=False, default=10)
346 t: int = 20
347
348 The class attribute :attr:`!C.z` will be ``10``, the class attribute
349 :attr:`!C.t` will be ``20``, and the class attributes :attr:`!C.x` and
350 :attr:`!C.y` will not be set.
351
352 .. class:: Field
353
354 :class:`!Field` objects describe each defined field. These objects
355 are created internally, and are returned by the :func:`fields`
356 module-level method (see below). Users should never instantiate a
357 :class:`!Field` object directly. Its documented attributes are:
358
359 - :attr:`!name`: The name of the field.
360 - :attr:`!type`: The type of the field.
361 - :attr:`!default`, :attr:`!default_factory`, :attr:`!init`, :attr:`!repr`, :attr:`!hash`,
362 :attr:`!compare`, :attr:`!metadata`, and :attr:`!kw_only` have the identical
363 meaning and values as they do in the :func:`field` function.
364
365 Other attributes may exist, but they are private and must not be
366 inspected or relied on.
367
368 .. class:: InitVar
369
370 ``InitVar[T]`` type annotations describe variables that are :ref:`init-only
371 <dataclasses-init-only-variables>`. Fields annotated with :class:`!InitVar`
372 are considered pseudo-fields, and thus are neither returned by the
373 :func:`fields` function nor used in any way except adding them as
374 parameters to :meth:`~object.__init__` and an optional
375 :meth:`__post_init__`.
376
377 .. function:: fields(class_or_instance)
378
379 Returns a tuple of :class:`Field` objects that define the fields for this
380 dataclass. Accepts either a dataclass, or an instance of a dataclass.
381 Raises :exc:`TypeError` if not passed a dataclass or instance of one.
382 Does not return pseudo-fields which are ``ClassVar`` or ``InitVar``.
383
384 .. function:: asdict(obj, *, dict_factory=dict)
385
386 Converts the dataclass *obj* to a dict (by using the
387 factory function *dict_factory*). Each dataclass is converted
388 to a dict of its fields, as ``name: value`` pairs. dataclasses, dicts,
389 lists, and tuples are recursed into. Other objects are copied with
390 :func:`copy.deepcopy`.
391
392 Example of using :func:`!asdict` on nested dataclasses::
393
394 @dataclass
395 class Point:
396 x: int
397 y: int
398
399 @dataclass
400 class C:
401 mylist: list[Point]
402
403 p = Point(10, 20)
404 assert asdict(p) == {'x': 10, 'y': 20}
405
406 c = C([Point(0, 0), Point(10, 4)])
407 assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
408
409 To create a shallow copy, the following workaround may be used::
410
411 {field.name: getattr(obj, field.name) for field in fields(obj)}
412
413 :func:`!asdict` raises :exc:`TypeError` if *obj* is not a dataclass
414 instance.
415
416 .. function:: astuple(obj, *, tuple_factory=tuple)
417
418 Converts the dataclass *obj* to a tuple (by using the
419 factory function *tuple_factory*). Each dataclass is converted
420 to a tuple of its field values. dataclasses, dicts, lists, and
421 tuples are recursed into. Other objects are copied with
422 :func:`copy.deepcopy`.
423
424 Continuing from the previous example::
425
426 assert astuple(p) == (10, 20)
427 assert astuple(c) == ([(0, 0), (10, 4)],)
428
429 To create a shallow copy, the following workaround may be used::
430
431 tuple(getattr(obj, field.name) for field in dataclasses.fields(obj))
432
433 :func:`!astuple` raises :exc:`TypeError` if *obj* is not a dataclass
434 instance.
435
436 .. function:: make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False, weakref_slot=False, module=None)
437
438 Creates a new dataclass with name *cls_name*, fields as defined
439 in *fields*, base classes as given in *bases*, and initialized
440 with a namespace as given in *namespace*. *fields* is an
441 iterable whose elements are each either ``name``, ``(name, type)``,
442 or ``(name, type, Field)``. If just ``name`` is supplied,
443 :data:`typing.Any` is used for ``type``. The values of *init*,
444 *repr*, *eq*, *order*, *unsafe_hash*, *frozen*,
445 *match_args*, *kw_only*, *slots*, and *weakref_slot* have
446 the same meaning as they do in :deco:`dataclass`.
447
448 If *module* is defined, the :attr:`!__module__` attribute
449 of the dataclass is set to that value.
450 By default, it is set to the module name of the caller.
451
452 This function is not strictly required, because any Python
453 mechanism for creating a new class with :attr:`!__annotations__` can
454 then apply the :deco:`dataclass` function to convert that class to
455 a dataclass. This function is provided as a convenience. For
456 example::
457
458 C = make_dataclass('C',
459 [('x', int),
460 'y',
461 ('z', int, field(default=5))],
462 namespace={'add_one': lambda self: self.x + 1})
463
464 Is equivalent to::
465
466 @dataclass
467 class C:
468 x: int
469 y: 'typing.Any'
470 z: int = 5
471
472 def add_one(self):
473 return self.x + 1
474
475 .. function:: replace(obj, /, **changes)
476
477 Creates a new object of the same type as *obj*, replacing
478 fields with values from *changes*. If *obj* is not a Data
479 Class, raises :exc:`TypeError`. If keys in *changes* are not
480 field names of the given dataclass, raises :exc:`TypeError`.
481
482 The newly returned object is created by calling the :meth:`~object.__init__`
483 method of the dataclass. This ensures that
484 :meth:`__post_init__`, if present, is also called.
485
486 Init-only variables without default values, if any exist, must be
487 specified on the call to :func:`!replace` so that they can be passed to
488 :meth:`!__init__` and :meth:`__post_init__`.
489
490 It is an error for *changes* to contain any fields that are
491 defined as having ``init=False``. A :exc:`ValueError` will be raised
492 in this case.
493
494 Be forewarned about how ``init=False`` fields work during a call to
495 :func:`!replace`. They are not copied from the source object, but
496 rather are initialized in :meth:`__post_init__`, if they're
497 initialized at all. It is expected that ``init=False`` fields will
498 be rarely and judiciously used. If they are used, it might be wise
499 to have alternate class constructors, or perhaps a custom
500 :func:`!replace` (or similarly named) method which handles instance
501 copying.
502
503 Dataclass instances are also supported by generic function :func:`copy.replace`.
504
505 .. function:: is_dataclass(obj)
506
507 Return ``True`` if its parameter is a dataclass (including subclasses of a
508 dataclass, but not including :ref:`generic aliases <types-genericalias>`)
509 or an instance of one, otherwise return ``False``.
510
511 If you need to know if a class is an instance of a dataclass (and
512 not a dataclass itself), then add a further check for ``not
513 isinstance(obj, type)``::
514
515 def is_dataclass_instance(obj):
516 return is_dataclass(obj) and not isinstance(obj, type)
517
518 .. data:: MISSING
519
520 A sentinel value signifying a missing default or default_factory.
521
522 .. data:: KW_ONLY
523
524 A sentinel value used as a type annotation. Any fields after a
525 pseudo-field with the type of :const:`!KW_ONLY` are marked as
526 keyword-only fields. Note that a pseudo-field of type
527 :const:`!KW_ONLY` is otherwise completely ignored. This includes the
528 name of such a field. By convention, a name of ``_`` is used for a
529 :const:`!KW_ONLY` field. Keyword-only fields signify
530 :meth:`~object.__init__` parameters that must be specified as keywords when
531 the class is instantiated.
532
533 In this example, the fields ``y`` and ``z`` will be marked as keyword-only fields::
534
535 @dataclass
536 class Point:
537 x: float
538 _: KW_ONLY
539 y: float
540 z: float
541
542 p = Point(0, y=1.5, z=2.0)
543
544 In a single dataclass, it is an error to specify more than one
545 field whose type is :const:`!KW_ONLY`.
546
547 .. versionadded:: 3.10
548
549 .. exception:: FrozenInstanceError
550
551 Raised when an implicitly defined :meth:`~object.__setattr__` or
552 :meth:`~object.__delattr__` is called on a dataclass which was defined with
553 ``frozen=True``. It is a subclass of :exc:`AttributeError`.
554
555 .. _post-init-processing:
556
557 Post-init processing
558 --------------------
559
560 .. function:: __post_init__()
561
562 When defined on the class, it will be called by the generated
563 :meth:`~object.__init__`, normally as :meth:`!self.__post_init__`.
564 However, if any ``InitVar`` fields are defined, they will also be
565 passed to :meth:`!__post_init__` in the order they were defined in the
566 class. If no :meth:`!__init__` method is generated, then
567 :meth:`!__post_init__` will not automatically be called.
568
569 Among other uses, this allows for initializing field values that
570 depend on one or more other fields. For example::
571
572 @dataclass
573 class C:
574 a: float
575 b: float
576 c: float = field(init=False)
577
578 def __post_init__(self):
579 self.c = self.a + self.b
580
581 The :meth:`~object.__init__` method generated by :deco:`dataclass` does not call base
582 class :meth:`!__init__` methods. If the base class has an :meth:`!__init__` method
583 that has to be called, it is common to call this method in a
584 :meth:`__post_init__` method::
585
586 class Rectangle:
587 def __init__(self, height, width):
588 self.height = height
589 self.width = width
590
591 @dataclass
592 class Square(Rectangle):
593 side: float
594
595 def __post_init__(self):
596 super().__init__(self.side, self.side)
597
598 Note, however, that in general the dataclass-generated :meth:`!__init__` methods
599 don't need to be called, since the derived dataclass will take care of
600 initializing all fields of any base class that is a dataclass itself.
601
602 See the section below on init-only variables for ways to pass
603 parameters to :meth:`!__post_init__`. Also see the warning about how
604 :func:`replace` handles ``init=False`` fields.
605
606 .. _dataclasses-class-variables:
607
608 Class variables
609 ---------------
610
611 One of the few places where :deco:`dataclass` actually inspects the type
612 of a field is to determine if a field is a class variable as defined
613 in :pep:`526`. It does this by checking if the type of the field is
614 :data:`typing.ClassVar`. If a field is a ``ClassVar``, it is excluded
615 from consideration as a field and is ignored by the dataclass
616 mechanisms. Such ``ClassVar`` pseudo-fields are not returned by the
617 module-level :func:`fields` function.
618
619 .. _dataclasses-init-only-variables:
620
621 Init-only variables
622 -------------------
623
624 Another place where :deco:`dataclass` inspects a type annotation is to
625 determine if a field is an init-only variable. It does this by seeing
626 if the type of a field is of type :class:`InitVar`. If a field
627 is an :class:`InitVar`, it is considered a pseudo-field called an init-only
628 field. As it is not a true field, it is not returned by the
629 module-level :func:`fields` function. Init-only fields are added as
630 parameters to the generated :meth:`~object.__init__` method, and are passed to
631 the optional :meth:`__post_init__` method. They are not otherwise used
632 by dataclasses.
633
634 For example, suppose a field will be initialized from a database, if a
635 value is not provided when creating the class::
636
637 @dataclass
638 class C:
639 i: int
640 j: int | None = None
641 database: InitVar[DatabaseType | None] = None
642
643 def __post_init__(self, database):
644 if self.j is None and database is not None:
645 self.j = database.lookup('j')
646
647 c = C(10, database=my_database)
648
649 In this case, :func:`fields` will return :class:`Field` objects for :attr:`!i` and
650 :attr:`!j`, but not for :attr:`!database`.
651
652 .. _dataclasses-frozen:
653
654 Frozen instances
655 ----------------
656
657 It is not possible to create truly immutable Python objects. However,
658 by passing ``frozen=True`` to the :deco:`dataclass` decorator you can
659 emulate immutability. In that case, dataclasses will add
660 :meth:`~object.__setattr__` and :meth:`~object.__delattr__` methods to the class. These
661 methods will raise a :exc:`FrozenInstanceError` when invoked.
662
663 There is a tiny performance penalty when using ``frozen=True``:
664 :meth:`~object.__init__` cannot use simple assignment to initialize fields, and
665 must use :meth:`!object.__setattr__`.
666
667 .. Make sure to not remove "object" from "object.__setattr__" in the above markup!
668
669 .. _dataclasses-inheritance:
670
671 Inheritance
672 -----------
673
674 When the dataclass is being created by the :deco:`dataclass` decorator,
675 it looks through all of the class's base classes in reverse MRO (that
676 is, starting at :class:`object`) and, for each dataclass that it finds,
677 adds the fields from that base class to an ordered mapping of fields.
678 After all of the base class fields are added, it adds its own fields
679 to the ordered mapping. All of the generated methods will use this
680 combined, calculated ordered mapping of fields. Because the fields
681 are in insertion order, derived classes override base classes. An
682 example::
683
684 @dataclass
685 class Base:
686 x: Any = 15.0
687 y: int = 0
688
689 @dataclass
690 class C(Base):
691 z: int = 10
692 x: int = 15
693
694 The final list of fields is, in order, :attr:`!x`, :attr:`!y`, :attr:`!z`. The final
695 type of :attr:`!x` is :class:`int`, as specified in class :class:`!C`.
696
697 The generated :meth:`~object.__init__` method for :class:`!C` will look like::
698
699 def __init__(self, x: int = 15, y: int = 0, z: int = 10):
700
701 Re-ordering of keyword-only parameters in :meth:`!__init__`
702 -----------------------------------------------------------
703
704 After the parameters needed for :meth:`~object.__init__` are computed, any
705 keyword-only parameters are moved to come after all regular
706 (non-keyword-only) parameters. This is a requirement of how
707 keyword-only parameters are implemented in Python: they must come
708 after non-keyword-only parameters.
709
710 In this example, :attr:`!Base.y`, :attr:`!Base.w`, and :attr:`!D.t` are keyword-only
711 fields, and :attr:`!Base.x` and :attr:`!D.z` are regular fields::
712
713 @dataclass
714 class Base:
715 x: Any = 15.0
716 _: KW_ONLY
717 y: int = 0
718 w: int = 1
719
720 @dataclass
721 class D(Base):
722 z: int = 10
723 t: int = field(kw_only=True, default=0)
724
725 The generated :meth:`!__init__` method for :class:`!D` will look like::
726
727 def __init__(self, x: Any = 15.0, z: int = 10, *, y: int = 0, w: int = 1, t: int = 0):
728
729 Note that the parameters have been re-ordered from how they appear in
730 the list of fields: parameters derived from regular fields are
731 followed by parameters derived from keyword-only fields.
732
733 The relative ordering of keyword-only parameters is maintained in the
734 re-ordered :meth:`!__init__` parameter list.
735
736
737 Default factory functions
738 -------------------------
739
740 If a :func:`field` specifies a *default_factory*, it is called with
741 zero arguments when a default value for the field is needed. For
742 example, to create a new instance of a list, use::
743
744 mylist: list = field(default_factory=list)
745
746 If a field is excluded from :meth:`~object.__init__` (using ``init=False``)
747 and the field also specifies *default_factory*, then the default
748 factory function will always be called from the generated
749 :meth:`!__init__` function. This happens because there is no other
750 way to give the field an initial value.
751
752 Mutable default values
753 ----------------------
754
755 Python stores default member variable values in class attributes.
756 Consider this example, not using dataclasses::
757
758 class C:
759 x = []
760 def add(self, element):
761 self.x.append(element)
762
763 o1 = C()
764 o2 = C()
765 o1.add(1)
766 o2.add(2)
767 assert o1.x == [1, 2]
768 assert o1.x is o2.x
769
770 Note that the two instances of class :class:`!C` share the same class
771 variable :attr:`!x`, as expected.
772
773 Using dataclasses, *if* this code was valid::
774
775 @dataclass
776 class D:
777 x: list = [] # This code raises ValueError
778 def add(self, element):
779 self.x.append(element)
780
781 it would generate code similar to::
782
783 class D:
784 x = []
785 def __init__(self, x=x):
786 self.x = x
787 def add(self, element):
788 self.x.append(element)
789
790 assert D().x is D().x
791
792 This has the same issue as the original example using class :class:`!C`.
793 That is, two instances of class :class:`!D` that do not specify a value
794 for :attr:`!x` when creating a class instance will share the same copy
795 of :attr:`!x`. Because dataclasses just use normal Python class
796 creation they also share this behavior. There is no general way
797 for Data Classes to detect this condition. Instead, the
798 :deco:`dataclass` decorator will raise a :exc:`ValueError` if it
799 detects an unhashable default parameter. The assumption is that if
800 a value is unhashable, it is mutable. This is a partial solution,
801 but it does protect against many common errors.
802
803 Using default factory functions is a way to create new instances of
804 mutable types as default values for fields::
805
806 @dataclass
807 class D:
808 x: list = field(default_factory=list)
809
810 assert D().x is not D().x
811
812 .. versionchanged:: 3.11
813 Instead of looking for and disallowing objects of type :class:`list`,
814 :class:`dict`, or :class:`set`, unhashable objects are now not allowed as
815 default values. Unhashability is used to approximate
816 mutability.
817
818 Descriptor-typed fields
819 -----------------------
820
821 Fields that are assigned :ref:`descriptor objects <descriptors>` as their
822 default value have the following special behaviors:
823
824 * The value for the field passed to the dataclass's :meth:`~object.__init__` method is
825 passed to the descriptor's :meth:`~object.__set__` method rather than overwriting the
826 descriptor object.
827
828 * Similarly, when getting or setting the field, the descriptor's
829 :meth:`~object.__get__` or :meth:`!__set__` method is called rather than returning or
830 overwriting the descriptor object.
831
832 * To determine whether a field contains a default value, :deco:`dataclass`
833 will call the descriptor's :meth:`!__get__` method using its class access
834 form: ``descriptor.__get__(obj=None, type=cls)``. If the
835 descriptor returns a value in this case, it will be used as the
836 field's default. On the other hand, if the descriptor raises
837 :exc:`AttributeError` in this situation, no default value will be
838 provided for the field.
839
840 ::
841
842 class IntConversionDescriptor:
843 def __init__(self, *, default):
844 self._default = default
845
846 def __set_name__(self, owner, name):
847 self._name = "_" + name
848
849 def __get__(self, obj, type):
850 if obj is None:
851 return self._default
852
853 return getattr(obj, self._name, self._default)
854
855 def __set__(self, obj, value):
856 setattr(obj, self._name, int(value))
857
858 @dataclass
859 class InventoryItem:
860 quantity_on_hand: IntConversionDescriptor = IntConversionDescriptor(default=100)
861
862 i = InventoryItem()
863 print(i.quantity_on_hand) # 100
864 i.quantity_on_hand = 2.5 # calls __set__ with 2.5
865 print(i.quantity_on_hand) # 2
866
867 Note that if a field is annotated with a descriptor type, but is not assigned
868 a descriptor object as its default value, the field will act like a normal
869 field.