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