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