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