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