blob: 0c0c7a8ddabfcb98cdecaad4220ec336065be00f [file] [log] [blame]
Eric V. Smith7a1c0272018-05-16 09:29:05 -04001:mod:`dataclasses` --- Data Classes
2===================================
Eric V. Smith98d50cb2018-05-16 04:20:43 -04003
4.. module:: dataclasses
Eric V. Smith7a1c0272018-05-16 09:29:05 -04005 :synopsis: Generate special methods on user-defined classes.
Eric V. Smith98d50cb2018-05-16 04:20:43 -04006
7.. moduleauthor:: Eric V. Smith <eric@trueblade.com>
8.. sectionauthor:: Eric V. Smith <eric@trueblade.com>
9
10**Source code:** :source:`Lib/dataclasses.py`
11
12--------------
13
14This module provides a decorator and functions for automatically
15adding generated :term:`special method`\s such as :meth:`__init__` and
16:meth:`__repr__` to user-defined classes. It was originally described
17in :pep:`557`.
18
19The member variables to use in these generated methods are defined
20using :pep:`526` type annotations. For example this code::
21
Ned Batchelder2effef72020-05-08 07:39:57 -040022 from dataclasses import dataclass
23
Eric V. Smith98d50cb2018-05-16 04:20:43 -040024 @dataclass
25 class InventoryItem:
marload61bb24a2020-07-09 21:13:47 +090026 """Class for keeping track of an item in inventory."""
Eric V. Smith98d50cb2018-05-16 04:20:43 -040027 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
34Will 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
41Note that this method is automatically added to the class: it is not
42directly specified in the ``InventoryItem`` definition shown above.
43
44.. versionadded:: 3.7
45
46Module-level decorators, classes, and functions
47-----------------------------------------------
48
Eric V. Smith750f4842021-04-10 21:28:42 -040049.. decorator:: dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True)
Eric V. Smith98d50cb2018-05-16 04:20:43 -040050
51 This function is a :term:`decorator` that is used to add generated
52 :term:`special method`\s to classes, as described below.
53
54 The :func:`dataclass` decorator examines the class to find
55 ``field``\s. A ``field`` is defined as class variable that has a
Cheryl Sabellab7105c92018-12-24 00:09:09 -050056 :term:`type annotation <variable annotation>`. With two
57 exceptions described below, nothing in :func:`dataclass`
58 examines the type specified in the variable annotation.
Eric V. Smith98d50cb2018-05-16 04:20:43 -040059
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 :func:`dataclass` decorator will add various "dunder" methods to
64 the class, described below. If any of the added methods already
Fabio Sangiovannie28aff52019-12-25 23:45:30 +010065 exist on the class, the behavior depends on the parameter, as documented
66 below. The decorator returns the same class that is called on; no new
67 class is created.
Eric V. Smith98d50cb2018-05-16 04:20:43 -040068
69 If :func:`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 :func:`dataclass` are
72 equivalent::
73
74 @dataclass
75 class C:
76 ...
77
78 @dataclass()
79 class C:
80 ...
81
Eric V. Smith750f4842021-04-10 21:28:42 -040082 @dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True)
Eric V. Smith98d50cb2018-05-16 04:20:43 -040083 class C:
84 ...
85
86 The parameters to :func:`dataclass` are:
87
88 - ``init``: If true (the default), a :meth:`__init__` method will be
89 generated.
90
91 If the class already defines :meth:`__init__`, this parameter is
92 ignored.
93
94 - ``repr``: If true (the default), a :meth:`__repr__` method will be
95 generated. The generated repr string will have the class name and
96 the name and repr of each field, in the order they are defined in
97 the class. Fields that are marked as being excluded from the repr
98 are not included. For example:
99 ``InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10)``.
100
101 If the class already defines :meth:`__repr__`, this parameter is
102 ignored.
103
104 - ``eq``: If true (the default), an :meth:`__eq__` method will be
105 generated. This method compares the class as if it were a tuple
106 of its fields, in order. Both instances in the comparison must
107 be of the identical type.
108
109 If the class already defines :meth:`__eq__`, this parameter is
110 ignored.
111
112 - ``order``: If true (the default is ``False``), :meth:`__lt__`,
113 :meth:`__le__`, :meth:`__gt__`, and :meth:`__ge__` methods will be
114 generated. These compare the class as if it were a tuple of its
115 fields, in order. Both instances in the comparison must be of the
116 identical type. If ``order`` is true and ``eq`` is false, a
117 :exc:`ValueError` is raised.
118
119 If the class already defines any of :meth:`__lt__`,
120 :meth:`__le__`, :meth:`__gt__`, or :meth:`__ge__`, then
Fabio Sangiovannie28aff52019-12-25 23:45:30 +0100121 :exc:`TypeError` is raised.
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400122
Barry Warsaw713a9362018-05-16 15:50:07 -0400123 - ``unsafe_hash``: If ``False`` (the default), a :meth:`__hash__` method
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400124 is generated according to how ``eq`` and ``frozen`` are set.
125
Barry Warsaw713a9362018-05-16 15:50:07 -0400126 :meth:`__hash__` is used by built-in :meth:`hash()`, and when objects are
127 added to hashed collections such as dictionaries and sets. Having a
128 :meth:`__hash__` implies that instances of the class are immutable.
129 Mutability is a complicated property that depends on the programmer's
130 intent, the existence and behavior of :meth:`__eq__`, and the values of
131 the ``eq`` and ``frozen`` flags in the :func:`dataclass` decorator.
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400132
Barry Warsaw713a9362018-05-16 15:50:07 -0400133 By default, :func:`dataclass` will not implicitly add a :meth:`__hash__`
134 method unless it is safe to do so. Neither will it add or change an
135 existing explicitly defined :meth:`__hash__` method. Setting the class
136 attribute ``__hash__ = None`` has a specific meaning to Python, as
137 described in the :meth:`__hash__` documentation.
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400138
Guilherme Martins Crocetti05540442021-03-08 19:50:39 -0300139 If :meth:`__hash__` is not explicitly defined, or if it is set to ``None``,
Barry Warsaw713a9362018-05-16 15:50:07 -0400140 then :func:`dataclass` *may* add an implicit :meth:`__hash__` method.
141 Although not recommended, you can force :func:`dataclass` to create a
142 :meth:`__hash__` method with ``unsafe_hash=True``. This might be the case
143 if your class is logically immutable but can nonetheless be mutated.
144 This is a specialized use case and should be considered carefully.
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400145
Barry Warsaw713a9362018-05-16 15:50:07 -0400146 Here are the rules governing implicit creation of a :meth:`__hash__`
147 method. Note that you cannot both have an explicit :meth:`__hash__`
148 method in your dataclass and set ``unsafe_hash=True``; this will result
149 in a :exc:`TypeError`.
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400150
Barry Warsaw713a9362018-05-16 15:50:07 -0400151 If ``eq`` and ``frozen`` are both true, by default :func:`dataclass` will
152 generate a :meth:`__hash__` method for you. If ``eq`` is true and
153 ``frozen`` is false, :meth:`__hash__` will be set to ``None``, marking it
154 unhashable (which it is, since it is mutable). If ``eq`` is false,
155 :meth:`__hash__` will be left untouched meaning the :meth:`__hash__`
156 method of the superclass will be used (if the superclass is
157 :class:`object`, this means it will fall back to id-based hashing).
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400158
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200159 - ``frozen``: If true (the default is ``False``), assigning to fields will
Barry Warsaw713a9362018-05-16 15:50:07 -0400160 generate an exception. This emulates read-only frozen instances. If
161 :meth:`__setattr__` or :meth:`__delattr__` is defined in the class, then
162 :exc:`TypeError` is raised. See the discussion below.
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400163
Eric V. Smith750f4842021-04-10 21:28:42 -0400164 - ``match_args``: If true (the default is ``True``), the
165 ``__match_args__`` tuple will be created from the list of
166 parameters to the generated :meth:`__init__` method (even if
167 :meth:`__init__` is not generated, see above). If false, or if
168 ``__match_args__`` is already defined in the class, then
169 ``__match_args__`` will not be generated.
170
171
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400172 ``field``\s may optionally specify a default value, using normal
173 Python syntax::
174
175 @dataclass
176 class C:
177 a: int # 'a' has no default value
178 b: int = 0 # assign a default value for 'b'
179
180 In this example, both ``a`` and ``b`` will be included in the added
181 :meth:`__init__` method, which will be defined as::
182
183 def __init__(self, a: int, b: int = 0):
184
185 :exc:`TypeError` will be raised if a field without a default value
186 follows a field with a default value. This is true either when this
187 occurs in a single class, or as a result of class inheritance.
188
189.. function:: field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata=None)
190
191 For common and simple use cases, no other functionality is
Barry Warsaw713a9362018-05-16 15:50:07 -0400192 required. There are, however, some dataclass features that
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400193 require additional per-field information. To satisfy this need for
194 additional information, you can replace the default field value
195 with a call to the provided :func:`field` function. For example::
196
197 @dataclass
198 class C:
Andre Delfino7f54e562020-10-03 19:10:59 -0300199 mylist: list[int] = field(default_factory=list)
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400200
201 c = C()
Barry Warsaw713a9362018-05-16 15:50:07 -0400202 c.mylist += [1, 2, 3]
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400203
204 As shown above, the ``MISSING`` value is a sentinel object used to
205 detect if the ``default`` and ``default_factory`` parameters are
206 provided. This sentinel is used because ``None`` is a valid value
207 for ``default``. No code should directly use the ``MISSING``
208 value.
209
210 The parameters to :func:`field` are:
211
212 - ``default``: If provided, this will be the default value for this
213 field. This is needed because the :meth:`field` call itself
214 replaces the normal position of the default value.
215
216 - ``default_factory``: If provided, it must be a zero-argument
217 callable that will be called when a default value is needed for
218 this field. Among other purposes, this can be used to specify
219 fields with mutable default values, as discussed below. It is an
220 error to specify both ``default`` and ``default_factory``.
221
222 - ``init``: If true (the default), this field is included as a
223 parameter to the generated :meth:`__init__` method.
224
225 - ``repr``: If true (the default), this field is included in the
226 string returned by the generated :meth:`__repr__` method.
227
228 - ``compare``: If true (the default), this field is included in the
229 generated equality and comparison methods (:meth:`__eq__`,
230 :meth:`__gt__`, et al.).
231
Barry Warsaw713a9362018-05-16 15:50:07 -0400232 - ``hash``: This can be a bool or ``None``. If true, this field is
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400233 included in the generated :meth:`__hash__` method. If ``None`` (the
234 default), use the value of ``compare``: this would normally be
235 the expected behavior. A field should be considered in the hash
236 if it's used for comparisons. Setting this value to anything
237 other than ``None`` is discouraged.
238
239 One possible reason to set ``hash=False`` but ``compare=True``
240 would be if a field is expensive to compute a hash value for,
241 that field is needed for equality testing, and there are other
242 fields that contribute to the type's hash value. Even if a field
243 is excluded from the hash, it will still be used for comparisons.
244
245 - ``metadata``: This can be a mapping or None. None is treated as
246 an empty dict. This value is wrapped in
247 :func:`~types.MappingProxyType` to make it read-only, and exposed
248 on the :class:`Field` object. It is not used at all by Data
249 Classes, and is provided as a third-party extension mechanism.
250 Multiple third-parties can each have their own key, to use as a
251 namespace in the metadata.
252
253 If the default value of a field is specified by a call to
254 :func:`field()`, then the class attribute for this field will be
255 replaced by the specified ``default`` value. If no ``default`` is
256 provided, then the class attribute will be deleted. The intent is
257 that after the :func:`dataclass` decorator runs, the class
258 attributes will all contain the default values for the fields, just
259 as if the default value itself were specified. For example,
260 after::
261
262 @dataclass
263 class C:
264 x: int
265 y: int = field(repr=False)
266 z: int = field(repr=False, default=10)
267 t: int = 20
268
269 The class attribute ``C.z`` will be ``10``, the class attribute
270 ``C.t`` will be ``20``, and the class attributes ``C.x`` and
271 ``C.y`` will not be set.
272
273.. class:: Field
274
275 :class:`Field` objects describe each defined field. These objects
276 are created internally, and are returned by the :func:`fields`
277 module-level method (see below). Users should never instantiate a
278 :class:`Field` object directly. Its documented attributes are:
279
280 - ``name``: The name of the field.
281
282 - ``type``: The type of the field.
283
284 - ``default``, ``default_factory``, ``init``, ``repr``, ``hash``,
285 ``compare``, and ``metadata`` have the identical meaning and
286 values as they do in the :func:`field` declaration.
287
288 Other attributes may exist, but they are private and must not be
289 inspected or relied on.
290
291.. function:: fields(class_or_instance)
292
Barry Warsaw713a9362018-05-16 15:50:07 -0400293 Returns a tuple of :class:`Field` objects that define the fields for this
294 dataclass. Accepts either a dataclass, or an instance of a dataclass.
295 Raises :exc:`TypeError` if not passed a dataclass or instance of one.
296 Does not return pseudo-fields which are ``ClassVar`` or ``InitVar``.
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400297
298.. function:: asdict(instance, *, dict_factory=dict)
299
Barry Warsaw713a9362018-05-16 15:50:07 -0400300 Converts the dataclass ``instance`` to a dict (by using the
301 factory function ``dict_factory``). Each dataclass is converted
302 to a dict of its fields, as ``name: value`` pairs. dataclasses, dicts,
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400303 lists, and tuples are recursed into. For example::
304
305 @dataclass
306 class Point:
307 x: int
308 y: int
309
310 @dataclass
311 class C:
Andre Delfino7f54e562020-10-03 19:10:59 -0300312 mylist: list[Point]
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400313
314 p = Point(10, 20)
315 assert asdict(p) == {'x': 10, 'y': 20}
316
317 c = C([Point(0, 0), Point(10, 4)])
Barry Warsaw713a9362018-05-16 15:50:07 -0400318 assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400319
Barry Warsaw713a9362018-05-16 15:50:07 -0400320 Raises :exc:`TypeError` if ``instance`` is not a dataclass instance.
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400321
방성범 (Bang Seongbeom)508d8202018-09-29 19:50:31 +0900322.. function:: astuple(instance, *, tuple_factory=tuple)
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400323
Barry Warsaw713a9362018-05-16 15:50:07 -0400324 Converts the dataclass ``instance`` to a tuple (by using the
325 factory function ``tuple_factory``). Each dataclass is converted
326 to a tuple of its field values. dataclasses, dicts, lists, and
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400327 tuples are recursed into.
328
329 Continuing from the previous example::
330
331 assert astuple(p) == (10, 20)
332 assert astuple(c) == ([(0, 0), (10, 4)],)
333
Barry Warsaw713a9362018-05-16 15:50:07 -0400334 Raises :exc:`TypeError` if ``instance`` is not a dataclass instance.
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400335
Eric V. Smith750f4842021-04-10 21:28:42 -0400336.. 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)
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400337
Barry Warsaw713a9362018-05-16 15:50:07 -0400338 Creates a new dataclass with name ``cls_name``, fields as defined
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400339 in ``fields``, base classes as given in ``bases``, and initialized
340 with a namespace as given in ``namespace``. ``fields`` is an
341 iterable whose elements are each either ``name``, ``(name, type)``,
342 or ``(name, type, Field)``. If just ``name`` is supplied,
343 ``typing.Any`` is used for ``type``. The values of ``init``,
Eric V. Smith750f4842021-04-10 21:28:42 -0400344 ``repr``, ``eq``, ``order``, ``unsafe_hash``, ``frozen``, and
345 ``match_args`` have the same meaning as they do in
346 :func:`dataclass`.
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400347
348 This function is not strictly required, because any Python
349 mechanism for creating a new class with ``__annotations__`` can
350 then apply the :func:`dataclass` function to convert that class to
Barry Warsaw713a9362018-05-16 15:50:07 -0400351 a dataclass. This function is provided as a convenience. For
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400352 example::
353
354 C = make_dataclass('C',
355 [('x', int),
356 'y',
357 ('z', int, field(default=5))],
358 namespace={'add_one': lambda self: self.x + 1})
359
360 Is equivalent to::
361
362 @dataclass
363 class C:
364 x: int
365 y: 'typing.Any'
366 z: int = 5
367
368 def add_one(self):
369 return self.x + 1
370
Serhiy Storchaka2d88e632019-06-26 19:07:44 +0300371.. function:: replace(instance, /, **changes)
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400372
373 Creates a new object of the same type of ``instance``, replacing
374 fields with values from ``changes``. If ``instance`` is not a Data
375 Class, raises :exc:`TypeError`. If values in ``changes`` do not
376 specify fields, raises :exc:`TypeError`.
377
378 The newly returned object is created by calling the :meth:`__init__`
Barry Warsaw713a9362018-05-16 15:50:07 -0400379 method of the dataclass. This ensures that
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400380 :meth:`__post_init__`, if present, is also called.
381
382 Init-only variables without default values, if any exist, must be
383 specified on the call to :func:`replace` so that they can be passed to
384 :meth:`__init__` and :meth:`__post_init__`.
385
Barry Warsaw713a9362018-05-16 15:50:07 -0400386 It is an error for ``changes`` to contain any fields that are
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400387 defined as having ``init=False``. A :exc:`ValueError` will be raised
388 in this case.
389
390 Be forewarned about how ``init=False`` fields work during a call to
391 :func:`replace`. They are not copied from the source object, but
392 rather are initialized in :meth:`__post_init__`, if they're
393 initialized at all. It is expected that ``init=False`` fields will
394 be rarely and judiciously used. If they are used, it might be wise
395 to have alternate class constructors, or perhaps a custom
396 ``replace()`` (or similarly named) method which handles instance
397 copying.
398
399.. function:: is_dataclass(class_or_instance)
400
Serhiy Storchaka138ccbb2019-11-12 16:57:03 +0200401 Return ``True`` if its parameter is a dataclass or an instance of one,
402 otherwise return ``False``.
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400403
404 If you need to know if a class is an instance of a dataclass (and
405 not a dataclass itself), then add a further check for ``not
406 isinstance(obj, type)``::
407
408 def is_dataclass_instance(obj):
409 return is_dataclass(obj) and not isinstance(obj, type)
410
411Post-init processing
412--------------------
413
414The generated :meth:`__init__` code will call a method named
415:meth:`__post_init__`, if :meth:`__post_init__` is defined on the
416class. It will normally be called as ``self.__post_init__()``.
417However, if any ``InitVar`` fields are defined, they will also be
Barry Warsaw713a9362018-05-16 15:50:07 -0400418passed to :meth:`__post_init__` in the order they were defined in the
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400419class. If no :meth:`__init__` method is generated, then
420:meth:`__post_init__` will not automatically be called.
421
422Among other uses, this allows for initializing field values that
423depend on one or more other fields. For example::
424
425 @dataclass
426 class C:
427 a: float
428 b: float
429 c: float = field(init=False)
430
431 def __post_init__(self):
432 self.c = self.a + self.b
433
434See the section below on init-only variables for ways to pass
435parameters to :meth:`__post_init__`. Also see the warning about how
436:func:`replace` handles ``init=False`` fields.
437
438Class variables
439---------------
440
441One of two places where :func:`dataclass` actually inspects the type
442of a field is to determine if a field is a class variable as defined
443in :pep:`526`. It does this by checking if the type of the field is
444``typing.ClassVar``. If a field is a ``ClassVar``, it is excluded
Barry Warsaw713a9362018-05-16 15:50:07 -0400445from consideration as a field and is ignored by the dataclass
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400446mechanisms. Such ``ClassVar`` pseudo-fields are not returned by the
447module-level :func:`fields` function.
448
449Init-only variables
450-------------------
451
452The other place where :func:`dataclass` inspects a type annotation is to
453determine if a field is an init-only variable. It does this by seeing
454if the type of a field is of type ``dataclasses.InitVar``. If a field
455is an ``InitVar``, it is considered a pseudo-field called an init-only
456field. As it is not a true field, it is not returned by the
457module-level :func:`fields` function. Init-only fields are added as
458parameters to the generated :meth:`__init__` method, and are passed to
459the optional :meth:`__post_init__` method. They are not otherwise used
Barry Warsaw713a9362018-05-16 15:50:07 -0400460by dataclasses.
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400461
Daniel Dương075b3c32018-08-24 16:19:24 +0700462For example, suppose a field will be initialized from a database, if a
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400463value is not provided when creating the class::
464
465 @dataclass
466 class C:
467 i: int
468 j: int = None
469 database: InitVar[DatabaseType] = None
470
471 def __post_init__(self, database):
472 if self.j is None and database is not None:
473 self.j = database.lookup('j')
474
475 c = C(10, database=my_database)
476
477In this case, :func:`fields` will return :class:`Field` objects for ``i`` and
478``j``, but not for ``database``.
479
480Frozen instances
481----------------
482
483It is not possible to create truly immutable Python objects. However,
484by passing ``frozen=True`` to the :meth:`dataclass` decorator you can
Barry Warsaw713a9362018-05-16 15:50:07 -0400485emulate immutability. In that case, dataclasses will add
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400486:meth:`__setattr__` and :meth:`__delattr__` methods to the class. These
487methods will raise a :exc:`FrozenInstanceError` when invoked.
488
489There is a tiny performance penalty when using ``frozen=True``:
490:meth:`__init__` cannot use simple assignment to initialize fields, and
491must use :meth:`object.__setattr__`.
492
493Inheritance
494-----------
495
Barry Warsaw713a9362018-05-16 15:50:07 -0400496When the dataclass is being created by the :meth:`dataclass` decorator,
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400497it looks through all of the class's base classes in reverse MRO (that
Barry Warsaw713a9362018-05-16 15:50:07 -0400498is, starting at :class:`object`) and, for each dataclass that it finds,
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400499adds the fields from that base class to an ordered mapping of fields.
500After all of the base class fields are added, it adds its own fields
501to the ordered mapping. All of the generated methods will use this
502combined, calculated ordered mapping of fields. Because the fields
503are in insertion order, derived classes override base classes. An
504example::
505
506 @dataclass
507 class Base:
508 x: Any = 15.0
509 y: int = 0
510
511 @dataclass
512 class C(Base):
513 z: int = 10
514 x: int = 15
515
516The final list of fields is, in order, ``x``, ``y``, ``z``. The final
517type of ``x`` is ``int``, as specified in class ``C``.
518
519The generated :meth:`__init__` method for ``C`` will look like::
520
521 def __init__(self, x: int = 15, y: int = 0, z: int = 10):
522
523Default factory functions
524-------------------------
525
526 If a :func:`field` specifies a ``default_factory``, it is called with
527 zero arguments when a default value for the field is needed. For
528 example, to create a new instance of a list, use::
529
Barry Warsaw713a9362018-05-16 15:50:07 -0400530 mylist: list = field(default_factory=list)
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400531
532 If a field is excluded from :meth:`__init__` (using ``init=False``)
533 and the field also specifies ``default_factory``, then the default
534 factory function will always be called from the generated
535 :meth:`__init__` function. This happens because there is no other
536 way to give the field an initial value.
537
538Mutable default values
539----------------------
540
541 Python stores default member variable values in class attributes.
Barry Warsaw713a9362018-05-16 15:50:07 -0400542 Consider this example, not using dataclasses::
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400543
544 class C:
545 x = []
546 def add(self, element):
Tom Faulknerda5e9472018-07-10 21:39:57 -0500547 self.x.append(element)
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400548
549 o1 = C()
550 o2 = C()
551 o1.add(1)
552 o2.add(2)
553 assert o1.x == [1, 2]
554 assert o1.x is o2.x
555
556 Note that the two instances of class ``C`` share the same class
557 variable ``x``, as expected.
558
Barry Warsaw713a9362018-05-16 15:50:07 -0400559 Using dataclasses, *if* this code was valid::
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400560
561 @dataclass
562 class D:
563 x: List = []
564 def add(self, element):
565 self.x += element
566
567 it would generate code similar to::
568
569 class D:
570 x = []
571 def __init__(self, x=x):
572 self.x = x
573 def add(self, element):
574 self.x += element
575
576 assert D().x is D().x
577
578 This has the same issue as the original example using class ``C``.
579 That is, two instances of class ``D`` that do not specify a value for
580 ``x`` when creating a class instance will share the same copy of
Barry Warsaw713a9362018-05-16 15:50:07 -0400581 ``x``. Because dataclasses just use normal Python class creation
582 they also share this behavior. There is no general way for Data
583 Classes to detect this condition. Instead, dataclasses will raise a
Eric V. Smith98d50cb2018-05-16 04:20:43 -0400584 :exc:`TypeError` if it detects a default parameter of type ``list``,
585 ``dict``, or ``set``. This is a partial solution, but it does protect
586 against many common errors.
587
588 Using default factory functions is a way to create new instances of
589 mutable types as default values for fields::
590
591 @dataclass
592 class D:
593 x: list = field(default_factory=list)
594
595 assert D().x is not D().x
Barry Warsaw713a9362018-05-16 15:50:07 -0400596
597Exceptions
598----------
599
600.. exception:: FrozenInstanceError
601
602 Raised when an implicitly defined :meth:`__setattr__` or
603 :meth:`__delattr__` is called on a dataclass which was defined with
604 ``frozen=True``.