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 <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 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 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 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) 50 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 a class variable that has a 56 :term:`type annotation <variable annotation>`. With two 57 exceptions described below, nothing in :func:`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 :func:`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 :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 82 @dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False) 83 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 121 :exc:`TypeError` is raised. 122 123 - ``unsafe_hash``: If ``False`` (the default), a :meth:`__hash__` method 124 is generated according to how ``eq`` and ``frozen`` are set. 125 126 :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. 132 133 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. 138 139 If :meth:`__hash__` is not explicitly defined, or if it is set to ``None``, 140 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. 145 146 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`. 150 151 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). 158 159 - ``frozen``: If true (the default is ``False``), assigning to fields will 160 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. 163 164 - ``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 .. versionadded:: 3.10 172 173 - ``kw_only``: If true (the default value is ``False``), then all 174 fields will be marked as keyword-only. If a field is marked as 175 keyword-only, then the only affect is that the :meth:`__init__` 176 parameter generated from a keyword-only field must be specified 177 with a keyword when :meth:`__init__` is called. There is no 178 effect on any other aspect of dataclasses. See the 179 :term:`parameter` glossary entry for details. Also see the 180 :const:`KW_ONLY` section. 181 182 .. versionadded:: 3.10 183 184 - ``slots``: If true (the default is ``False``), :attr:`__slots__` attribute 185 will be generated and new class will be returned instead of the original one. 186 If :attr:`__slots__` is already defined in the class, then :exc:`TypeError` 187 is raised. 188 189 .. versionadded:: 3.10 190 191 ``field``\s may optionally specify a default value, using normal 192 Python syntax:: 193 194 @dataclass 195 class C: 196 a: int # 'a' has no default value 197 b: int = 0 # assign a default value for 'b' 198 199 In this example, both ``a`` and ``b`` will be included in the added 200 :meth:`__init__` method, which will be defined as:: 201 202 def __init__(self, a: int, b: int = 0): 203 204 :exc:`TypeError` will be raised if a field without a default value 205 follows a field with a default value. This is true whether this 206 occurs in a single class, or as a result of class inheritance. 207 208.. function:: field(*, default=MISSING, default_factory=MISSING, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=MISSING) 209 210 For common and simple use cases, no other functionality is 211 required. There are, however, some dataclass features that 212 require additional per-field information. To satisfy this need for 213 additional information, you can replace the default field value 214 with a call to the provided :func:`field` function. For example:: 215 216 @dataclass 217 class C: 218 mylist: list[int] = field(default_factory=list) 219 220 c = C() 221 c.mylist += [1, 2, 3] 222 223 As shown above, the :const:`MISSING` value is a sentinel object used to 224 detect if some parameters are provided by the user. This sentinel is 225 used because ``None`` is a valid value for some parameters with 226 a distinct meaning. No code should directly use the :const:`MISSING` value. 227 228 The parameters to :func:`field` are: 229 230 - ``default``: If provided, this will be the default value for this 231 field. This is needed because the :meth:`field` call itself 232 replaces the normal position of the default value. 233 234 - ``default_factory``: If provided, it must be a zero-argument 235 callable that will be called when a default value is needed for 236 this field. Among other purposes, this can be used to specify 237 fields with mutable default values, as discussed below. It is an 238 error to specify both ``default`` and ``default_factory``. 239 240 - ``init``: If true (the default), this field is included as a 241 parameter to the generated :meth:`__init__` method. 242 243 - ``repr``: If true (the default), this field is included in the 244 string returned by the generated :meth:`__repr__` method. 245 246 - ``hash``: This can be a bool or ``None``. If true, this field is 247 included in the generated :meth:`__hash__` method. If ``None`` (the 248 default), use the value of ``compare``: this would normally be 249 the expected behavior. A field should be considered in the hash 250 if it's used for comparisons. Setting this value to anything 251 other than ``None`` is discouraged. 252 253 One possible reason to set ``hash=False`` but ``compare=True`` 254 would be if a field is expensive to compute a hash value for, 255 that field is needed for equality testing, and there are other 256 fields that contribute to the type's hash value. Even if a field 257 is excluded from the hash, it will still be used for comparisons. 258 259 - ``compare``: If true (the default), this field is included in the 260 generated equality and comparison methods (:meth:`__eq__`, 261 :meth:`__gt__`, et al.). 262 263 - ``metadata``: This can be a mapping or None. None is treated as 264 an empty dict. This value is wrapped in 265 :func:`~types.MappingProxyType` to make it read-only, and exposed 266 on the :class:`Field` object. It is not used at all by Data 267 Classes, and is provided as a third-party extension mechanism. 268 Multiple third-parties can each have their own key, to use as a 269 namespace in the metadata. 270 271 - ``kw_only``: If true, this field will be marked as keyword-only. 272 This is used when the generated :meth:`__init__` method's 273 parameters are computed. 274 275 .. versionadded:: 3.10 276 277 If the default value of a field is specified by a call to 278 :func:`field()`, then the class attribute for this field will be 279 replaced by the specified ``default`` value. If no ``default`` is 280 provided, then the class attribute will be deleted. The intent is 281 that after the :func:`dataclass` decorator runs, the class 282 attributes will all contain the default values for the fields, just 283 as if the default value itself were specified. For example, 284 after:: 285 286 @dataclass 287 class C: 288 x: int 289 y: int = field(repr=False) 290 z: int = field(repr=False, default=10) 291 t: int = 20 292 293 The class attribute ``C.z`` will be ``10``, the class attribute 294 ``C.t`` will be ``20``, and the class attributes ``C.x`` and 295 ``C.y`` will not be set. 296 297.. class:: Field 298 299 :class:`Field` objects describe each defined field. These objects 300 are created internally, and are returned by the :func:`fields` 301 module-level method (see below). Users should never instantiate a 302 :class:`Field` object directly. Its documented attributes are: 303 304 - ``name``: The name of the field. 305 306 - ``type``: The type of the field. 307 308 - ``default``, ``default_factory``, ``init``, ``repr``, ``hash``, 309 ``compare``, ``metadata``, and ``kw_only`` have the identical 310 meaning and values as they do in the :func:`field` function. 311 312 Other attributes may exist, but they are private and must not be 313 inspected or relied on. 314 315.. function:: fields(class_or_instance) 316 317 Returns a tuple of :class:`Field` objects that define the fields for this 318 dataclass. Accepts either a dataclass, or an instance of a dataclass. 319 Raises :exc:`TypeError` if not passed a dataclass or instance of one. 320 Does not return pseudo-fields which are ``ClassVar`` or ``InitVar``. 321 322.. function:: asdict(obj, *, dict_factory=dict) 323 324 Converts the dataclass ``obj`` to a dict (by using the 325 factory function ``dict_factory``). Each dataclass is converted 326 to a dict of its fields, as ``name: value`` pairs. dataclasses, dicts, 327 lists, and tuples are recursed into. Other objects are copied with 328 :func:`copy.deepcopy`. 329 330 Example of using :func:`asdict` on nested dataclasses:: 331 332 @dataclass 333 class Point: 334 x: int 335 y: int 336 337 @dataclass 338 class C: 339 mylist: list[Point] 340 341 p = Point(10, 20) 342 assert asdict(p) == {'x': 10, 'y': 20} 343 344 c = C([Point(0, 0), Point(10, 4)]) 345 assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]} 346 347 To create a shallow copy, the following workaround may be used:: 348 349 dict((field.name, getattr(obj, field.name)) for field in fields(obj)) 350 351 :func:`asdict` raises :exc:`TypeError` if ``obj`` is not a dataclass 352 instance. 353 354.. function:: astuple(obj, *, tuple_factory=tuple) 355 356 Converts the dataclass ``obj`` to a tuple (by using the 357 factory function ``tuple_factory``). Each dataclass is converted 358 to a tuple of its field values. dataclasses, dicts, lists, and 359 tuples are recursed into. Other objects are copied with 360 :func:`copy.deepcopy`. 361 362 Continuing from the previous example:: 363 364 assert astuple(p) == (10, 20) 365 assert astuple(c) == ([(0, 0), (10, 4)],) 366 367 To create a shallow copy, the following workaround may be used:: 368 369 tuple(getattr(obj, field.name) for field in dataclasses.fields(obj)) 370 371 :func:`astuple` raises :exc:`TypeError` if ``obj`` is not a dataclass 372 instance. 373 374.. 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) 375 376 Creates a new dataclass with name ``cls_name``, fields as defined 377 in ``fields``, base classes as given in ``bases``, and initialized 378 with a namespace as given in ``namespace``. ``fields`` is an 379 iterable whose elements are each either ``name``, ``(name, type)``, 380 or ``(name, type, Field)``. If just ``name`` is supplied, 381 ``typing.Any`` is used for ``type``. The values of ``init``, 382 ``repr``, ``eq``, ``order``, ``unsafe_hash``, ``frozen``, 383 ``match_args``, ``kw_only``, and ``slots`` have the same meaning as 384 they do in :func:`dataclass`. 385 386 This function is not strictly required, because any Python 387 mechanism for creating a new class with ``__annotations__`` can 388 then apply the :func:`dataclass` function to convert that class to 389 a dataclass. This function is provided as a convenience. For 390 example:: 391 392 C = make_dataclass('C', 393 [('x', int), 394 'y', 395 ('z', int, field(default=5))], 396 namespace={'add_one': lambda self: self.x + 1}) 397 398 Is equivalent to:: 399 400 @dataclass 401 class C: 402 x: int 403 y: 'typing.Any' 404 z: int = 5 405 406 def add_one(self): 407 return self.x + 1 408 409.. function:: replace(obj, /, **changes) 410 411 Creates a new object of the same type as ``obj``, replacing 412 fields with values from ``changes``. If ``obj`` is not a Data 413 Class, raises :exc:`TypeError`. If values in ``changes`` do not 414 specify fields, raises :exc:`TypeError`. 415 416 The newly returned object is created by calling the :meth:`__init__` 417 method of the dataclass. This ensures that 418 :meth:`__post_init__`, if present, is also called. 419 420 Init-only variables without default values, if any exist, must be 421 specified on the call to :func:`replace` so that they can be passed to 422 :meth:`__init__` and :meth:`__post_init__`. 423 424 It is an error for ``changes`` to contain any fields that are 425 defined as having ``init=False``. A :exc:`ValueError` will be raised 426 in this case. 427 428 Be forewarned about how ``init=False`` fields work during a call to 429 :func:`replace`. They are not copied from the source object, but 430 rather are initialized in :meth:`__post_init__`, if they're 431 initialized at all. It is expected that ``init=False`` fields will 432 be rarely and judiciously used. If they are used, it might be wise 433 to have alternate class constructors, or perhaps a custom 434 ``replace()`` (or similarly named) method which handles instance 435 copying. 436 437.. function:: is_dataclass(obj) 438 439 Return ``True`` if its parameter is a dataclass or an instance of one, 440 otherwise return ``False``. 441 442 If you need to know if a class is an instance of a dataclass (and 443 not a dataclass itself), then add a further check for ``not 444 isinstance(obj, type)``:: 445 446 def is_dataclass_instance(obj): 447 return is_dataclass(obj) and not isinstance(obj, type) 448 449.. data:: MISSING 450 451 A sentinel value signifying a missing default or default_factory. 452 453.. data:: KW_ONLY 454 455 A sentinel value used as a type annotation. Any fields after a 456 pseudo-field with the type of :const:`KW_ONLY` are marked as 457 keyword-only fields. Note that a pseudo-field of type 458 :const:`KW_ONLY` is otherwise completely ignored. This includes the 459 name of such a field. By convention, a name of ``_`` is used for a 460 :const:`KW_ONLY` field. Keyword-only fields signify 461 :meth:`__init__` parameters that must be specified as keywords when 462 the class is instantiated. 463 464 In this example, the fields ``y`` and ``z`` will be marked as keyword-only fields:: 465 466 @dataclass 467 class Point: 468 x: float 469 _: KW_ONLY 470 y: float 471 z: float 472 473 p = Point(0, y=1.5, z=2.0) 474 475 In a single dataclass, it is an error to specify more than one 476 field whose type is :const:`KW_ONLY`. 477 478.. exception:: FrozenInstanceError 479 480 Raised when an implicitly defined :meth:`__setattr__` or 481 :meth:`__delattr__` is called on a dataclass which was defined with 482 ``frozen=True``. It is a subclass of :exc:`AttributeError`. 483 484Post-init processing 485-------------------- 486 487The generated :meth:`__init__` code will call a method named 488:meth:`__post_init__`, if :meth:`__post_init__` is defined on the 489class. It will normally be called as ``self.__post_init__()``. 490However, if any ``InitVar`` fields are defined, they will also be 491passed to :meth:`__post_init__` in the order they were defined in the 492class. If no :meth:`__init__` method is generated, then 493:meth:`__post_init__` will not automatically be called. 494 495Among other uses, this allows for initializing field values that 496depend on one or more other fields. For example:: 497 498 @dataclass 499 class C: 500 a: float 501 b: float 502 c: float = field(init=False) 503 504 def __post_init__(self): 505 self.c = self.a + self.b 506 507The :meth:`__init__` method generated by :func:`dataclass` does not call base 508class :meth:`__init__` methods. If the base class has an :meth:`__init__` method 509that has to be called, it is common to call this method in a 510:meth:`__post_init__` method:: 511 512 @dataclass 513 class Rectangle: 514 height: float 515 width: float 516 517 @dataclass 518 class Square(Rectangle): 519 side: float 520 521 def __post_init__(self): 522 super().__init__(self.side, self.side) 523 524Note, however, that in general the dataclass-generated :meth:`__init__` methods 525don't need to be called, since the derived dataclass will take care of 526initializing all fields of any base class that is a dataclass itself. 527 528See the section below on init-only variables for ways to pass 529parameters to :meth:`__post_init__`. Also see the warning about how 530:func:`replace` handles ``init=False`` fields. 531 532Class variables 533--------------- 534 535One of two places where :func:`dataclass` actually inspects the type 536of a field is to determine if a field is a class variable as defined 537in :pep:`526`. It does this by checking if the type of the field is 538``typing.ClassVar``. If a field is a ``ClassVar``, it is excluded 539from consideration as a field and is ignored by the dataclass 540mechanisms. Such ``ClassVar`` pseudo-fields are not returned by the 541module-level :func:`fields` function. 542 543Init-only variables 544------------------- 545 546The other place where :func:`dataclass` inspects a type annotation is to 547determine if a field is an init-only variable. It does this by seeing 548if the type of a field is of type ``dataclasses.InitVar``. If a field 549is an ``InitVar``, it is considered a pseudo-field called an init-only 550field. As it is not a true field, it is not returned by the 551module-level :func:`fields` function. Init-only fields are added as 552parameters to the generated :meth:`__init__` method, and are passed to 553the optional :meth:`__post_init__` method. They are not otherwise used 554by dataclasses. 555 556For example, suppose a field will be initialized from a database, if a 557value is not provided when creating the class:: 558 559 @dataclass 560 class C: 561 i: int 562 j: int = None 563 database: InitVar[DatabaseType] = None 564 565 def __post_init__(self, database): 566 if self.j is None and database is not None: 567 self.j = database.lookup('j') 568 569 c = C(10, database=my_database) 570 571In this case, :func:`fields` will return :class:`Field` objects for ``i`` and 572``j``, but not for ``database``. 573 574Frozen instances 575---------------- 576 577It is not possible to create truly immutable Python objects. However, 578by passing ``frozen=True`` to the :meth:`dataclass` decorator you can 579emulate immutability. In that case, dataclasses will add 580:meth:`__setattr__` and :meth:`__delattr__` methods to the class. These 581methods will raise a :exc:`FrozenInstanceError` when invoked. 582 583There is a tiny performance penalty when using ``frozen=True``: 584:meth:`__init__` cannot use simple assignment to initialize fields, and 585must use :meth:`object.__setattr__`. 586 587Inheritance 588----------- 589 590When the dataclass is being created by the :meth:`dataclass` decorator, 591it looks through all of the class's base classes in reverse MRO (that 592is, starting at :class:`object`) and, for each dataclass that it finds, 593adds the fields from that base class to an ordered mapping of fields. 594After all of the base class fields are added, it adds its own fields 595to the ordered mapping. All of the generated methods will use this 596combined, calculated ordered mapping of fields. Because the fields 597are in insertion order, derived classes override base classes. An 598example:: 599 600 @dataclass 601 class Base: 602 x: Any = 15.0 603 y: int = 0 604 605 @dataclass 606 class C(Base): 607 z: int = 10 608 x: int = 15 609 610The final list of fields is, in order, ``x``, ``y``, ``z``. The final 611type of ``x`` is ``int``, as specified in class ``C``. 612 613The generated :meth:`__init__` method for ``C`` will look like:: 614 615 def __init__(self, x: int = 15, y: int = 0, z: int = 10): 616 617Re-ordering of keyword-only parameters in :meth:`__init__` 618---------------------------------------------------------- 619 620After the parameters needed for :meth:`__init__` are computed, any 621keyword-only parameters are moved to come after all regular 622(non-keyword-only) parameters. This is a requirement of how 623keyword-only parameters are implemented in Python: they must come 624after non-keyword-only parameters. 625 626In this example, ``Base.y``, ``Base.w``, and ``D.t`` are keyword-only 627fields, and ``Base.x`` and ``D.z`` are regular fields:: 628 629 @dataclass 630 class Base: 631 x: Any = 15.0 632 _: KW_ONLY 633 y: int = 0 634 w: int = 1 635 636 @dataclass 637 class D(Base): 638 z: int = 10 639 t: int = field(kw_only=True, default=0) 640 641The generated :meth:`__init__` method for ``D`` will look like:: 642 643 def __init__(self, x: Any = 15.0, z: int = 10, *, y: int = 0, w: int = 1, t: int = 0): 644 645Note that the parameters have been re-ordered from how they appear in 646the list of fields: parameters derived from regular fields are 647followed by parameters derived from keyword-only fields. 648 649The relative ordering of keyword-only parameters is maintained in the 650re-ordered :meth:`__init__` parameter list. 651 652 653Default factory functions 654------------------------- 655 656 If a :func:`field` specifies a ``default_factory``, it is called with 657 zero arguments when a default value for the field is needed. For 658 example, to create a new instance of a list, use:: 659 660 mylist: list = field(default_factory=list) 661 662 If a field is excluded from :meth:`__init__` (using ``init=False``) 663 and the field also specifies ``default_factory``, then the default 664 factory function will always be called from the generated 665 :meth:`__init__` function. This happens because there is no other 666 way to give the field an initial value. 667 668Mutable default values 669---------------------- 670 671 Python stores default member variable values in class attributes. 672 Consider this example, not using dataclasses:: 673 674 class C: 675 x = [] 676 def add(self, element): 677 self.x.append(element) 678 679 o1 = C() 680 o2 = C() 681 o1.add(1) 682 o2.add(2) 683 assert o1.x == [1, 2] 684 assert o1.x is o2.x 685 686 Note that the two instances of class ``C`` share the same class 687 variable ``x``, as expected. 688 689 Using dataclasses, *if* this code was valid:: 690 691 @dataclass 692 class D: 693 x: List = [] 694 def add(self, element): 695 self.x += element 696 697 it would generate code similar to:: 698 699 class D: 700 x = [] 701 def __init__(self, x=x): 702 self.x = x 703 def add(self, element): 704 self.x += element 705 706 assert D().x is D().x 707 708 This has the same issue as the original example using class ``C``. 709 That is, two instances of class ``D`` that do not specify a value 710 for ``x`` when creating a class instance will share the same copy 711 of ``x``. Because dataclasses just use normal Python class 712 creation they also share this behavior. There is no general way 713 for Data Classes to detect this condition. Instead, the 714 :func:`dataclass` decorator will raise a :exc:`TypeError` if it 715 detects a default parameter of type ``list``, ``dict``, or ``set``. 716 This is a partial solution, but it does protect against many common 717 errors. 718 719 Using default factory functions is a way to create new instances of 720 mutable types as default values for fields:: 721 722 @dataclass 723 class D: 724 x: list = field(default_factory=list) 725 726 assert D().x is not D().x 727