17db96d56Sopenharmony_ci:mod:`dataclasses` --- Data Classes 27db96d56Sopenharmony_ci=================================== 37db96d56Sopenharmony_ci 47db96d56Sopenharmony_ci.. module:: dataclasses 57db96d56Sopenharmony_ci :synopsis: Generate special methods on user-defined classes. 67db96d56Sopenharmony_ci 77db96d56Sopenharmony_ci.. moduleauthor:: Eric V. Smith <eric@trueblade.com> 87db96d56Sopenharmony_ci.. sectionauthor:: Eric V. Smith <eric@trueblade.com> 97db96d56Sopenharmony_ci 107db96d56Sopenharmony_ci**Source code:** :source:`Lib/dataclasses.py` 117db96d56Sopenharmony_ci 127db96d56Sopenharmony_ci-------------- 137db96d56Sopenharmony_ci 147db96d56Sopenharmony_ciThis module provides a decorator and functions for automatically 157db96d56Sopenharmony_ciadding generated :term:`special method`\s such as :meth:`~object.__init__` and 167db96d56Sopenharmony_ci:meth:`~object.__repr__` to user-defined classes. It was originally described 177db96d56Sopenharmony_ciin :pep:`557`. 187db96d56Sopenharmony_ci 197db96d56Sopenharmony_ciThe member variables to use in these generated methods are defined 207db96d56Sopenharmony_ciusing :pep:`526` type annotations. For example, this code:: 217db96d56Sopenharmony_ci 227db96d56Sopenharmony_ci from dataclasses import dataclass 237db96d56Sopenharmony_ci 247db96d56Sopenharmony_ci @dataclass 257db96d56Sopenharmony_ci class InventoryItem: 267db96d56Sopenharmony_ci """Class for keeping track of an item in inventory.""" 277db96d56Sopenharmony_ci name: str 287db96d56Sopenharmony_ci unit_price: float 297db96d56Sopenharmony_ci quantity_on_hand: int = 0 307db96d56Sopenharmony_ci 317db96d56Sopenharmony_ci def total_cost(self) -> float: 327db96d56Sopenharmony_ci return self.unit_price * self.quantity_on_hand 337db96d56Sopenharmony_ci 347db96d56Sopenharmony_ciwill add, among other things, a :meth:`~object.__init__` that looks like:: 357db96d56Sopenharmony_ci 367db96d56Sopenharmony_ci def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0): 377db96d56Sopenharmony_ci self.name = name 387db96d56Sopenharmony_ci self.unit_price = unit_price 397db96d56Sopenharmony_ci self.quantity_on_hand = quantity_on_hand 407db96d56Sopenharmony_ci 417db96d56Sopenharmony_ciNote that this method is automatically added to the class: it is not 427db96d56Sopenharmony_cidirectly specified in the ``InventoryItem`` definition shown above. 437db96d56Sopenharmony_ci 447db96d56Sopenharmony_ci.. versionadded:: 3.7 457db96d56Sopenharmony_ci 467db96d56Sopenharmony_ciModule contents 477db96d56Sopenharmony_ci--------------- 487db96d56Sopenharmony_ci 497db96d56Sopenharmony_ci.. 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) 507db96d56Sopenharmony_ci 517db96d56Sopenharmony_ci This function is a :term:`decorator` that is used to add generated 527db96d56Sopenharmony_ci :term:`special method`\s to classes, as described below. 537db96d56Sopenharmony_ci 547db96d56Sopenharmony_ci The :func:`dataclass` decorator examines the class to find 557db96d56Sopenharmony_ci ``field``\s. A ``field`` is defined as a class variable that has a 567db96d56Sopenharmony_ci :term:`type annotation <variable annotation>`. With two 577db96d56Sopenharmony_ci exceptions described below, nothing in :func:`dataclass` 587db96d56Sopenharmony_ci examines the type specified in the variable annotation. 597db96d56Sopenharmony_ci 607db96d56Sopenharmony_ci The order of the fields in all of the generated methods is the 617db96d56Sopenharmony_ci order in which they appear in the class definition. 627db96d56Sopenharmony_ci 637db96d56Sopenharmony_ci The :func:`dataclass` decorator will add various "dunder" methods to 647db96d56Sopenharmony_ci the class, described below. If any of the added methods already 657db96d56Sopenharmony_ci exist in the class, the behavior depends on the parameter, as documented 667db96d56Sopenharmony_ci below. The decorator returns the same class that it is called on; no new 677db96d56Sopenharmony_ci class is created. 687db96d56Sopenharmony_ci 697db96d56Sopenharmony_ci If :func:`dataclass` is used just as a simple decorator with no parameters, 707db96d56Sopenharmony_ci it acts as if it has the default values documented in this 717db96d56Sopenharmony_ci signature. That is, these three uses of :func:`dataclass` are 727db96d56Sopenharmony_ci equivalent:: 737db96d56Sopenharmony_ci 747db96d56Sopenharmony_ci @dataclass 757db96d56Sopenharmony_ci class C: 767db96d56Sopenharmony_ci ... 777db96d56Sopenharmony_ci 787db96d56Sopenharmony_ci @dataclass() 797db96d56Sopenharmony_ci class C: 807db96d56Sopenharmony_ci ... 817db96d56Sopenharmony_ci 827db96d56Sopenharmony_ci @dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, 837db96d56Sopenharmony_ci match_args=True, kw_only=False, slots=False, weakref_slot=False) 847db96d56Sopenharmony_ci class C: 857db96d56Sopenharmony_ci ... 867db96d56Sopenharmony_ci 877db96d56Sopenharmony_ci The parameters to :func:`dataclass` are: 887db96d56Sopenharmony_ci 897db96d56Sopenharmony_ci - ``init``: If true (the default), a :meth:`~object.__init__` method will be 907db96d56Sopenharmony_ci generated. 917db96d56Sopenharmony_ci 927db96d56Sopenharmony_ci If the class already defines :meth:`~object.__init__`, this parameter is 937db96d56Sopenharmony_ci ignored. 947db96d56Sopenharmony_ci 957db96d56Sopenharmony_ci - ``repr``: If true (the default), a :meth:`~object.__repr__` method will be 967db96d56Sopenharmony_ci generated. The generated repr string will have the class name and 977db96d56Sopenharmony_ci the name and repr of each field, in the order they are defined in 987db96d56Sopenharmony_ci the class. Fields that are marked as being excluded from the repr 997db96d56Sopenharmony_ci are not included. For example: 1007db96d56Sopenharmony_ci ``InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10)``. 1017db96d56Sopenharmony_ci 1027db96d56Sopenharmony_ci If the class already defines :meth:`~object.__repr__`, this parameter is 1037db96d56Sopenharmony_ci ignored. 1047db96d56Sopenharmony_ci 1057db96d56Sopenharmony_ci - ``eq``: If true (the default), an :meth:`~object.__eq__` method will be 1067db96d56Sopenharmony_ci generated. This method compares the class as if it were a tuple 1077db96d56Sopenharmony_ci of its fields, in order. Both instances in the comparison must 1087db96d56Sopenharmony_ci be of the identical type. 1097db96d56Sopenharmony_ci 1107db96d56Sopenharmony_ci If the class already defines :meth:`~object.__eq__`, this parameter is 1117db96d56Sopenharmony_ci ignored. 1127db96d56Sopenharmony_ci 1137db96d56Sopenharmony_ci - ``order``: If true (the default is ``False``), :meth:`~object.__lt__`, 1147db96d56Sopenharmony_ci :meth:`~object.__le__`, :meth:`~object.__gt__`, and :meth:`~object.__ge__` methods will be 1157db96d56Sopenharmony_ci generated. These compare the class as if it were a tuple of its 1167db96d56Sopenharmony_ci fields, in order. Both instances in the comparison must be of the 1177db96d56Sopenharmony_ci identical type. If ``order`` is true and ``eq`` is false, a 1187db96d56Sopenharmony_ci :exc:`ValueError` is raised. 1197db96d56Sopenharmony_ci 1207db96d56Sopenharmony_ci If the class already defines any of :meth:`~object.__lt__`, 1217db96d56Sopenharmony_ci :meth:`~object.__le__`, :meth:`~object.__gt__`, or :meth:`~object.__ge__`, then 1227db96d56Sopenharmony_ci :exc:`TypeError` is raised. 1237db96d56Sopenharmony_ci 1247db96d56Sopenharmony_ci - ``unsafe_hash``: If ``False`` (the default), a :meth:`~object.__hash__` method 1257db96d56Sopenharmony_ci is generated according to how ``eq`` and ``frozen`` are set. 1267db96d56Sopenharmony_ci 1277db96d56Sopenharmony_ci :meth:`~object.__hash__` is used by built-in :meth:`hash()`, and when objects are 1287db96d56Sopenharmony_ci added to hashed collections such as dictionaries and sets. Having a 1297db96d56Sopenharmony_ci :meth:`~object.__hash__` implies that instances of the class are immutable. 1307db96d56Sopenharmony_ci Mutability is a complicated property that depends on the programmer's 1317db96d56Sopenharmony_ci intent, the existence and behavior of :meth:`~object.__eq__`, and the values of 1327db96d56Sopenharmony_ci the ``eq`` and ``frozen`` flags in the :func:`dataclass` decorator. 1337db96d56Sopenharmony_ci 1347db96d56Sopenharmony_ci By default, :func:`dataclass` will not implicitly add a :meth:`~object.__hash__` 1357db96d56Sopenharmony_ci method unless it is safe to do so. Neither will it add or change an 1367db96d56Sopenharmony_ci existing explicitly defined :meth:`~object.__hash__` method. Setting the class 1377db96d56Sopenharmony_ci attribute ``__hash__ = None`` has a specific meaning to Python, as 1387db96d56Sopenharmony_ci described in the :meth:`~object.__hash__` documentation. 1397db96d56Sopenharmony_ci 1407db96d56Sopenharmony_ci If :meth:`~object.__hash__` is not explicitly defined, or if it is set to ``None``, 1417db96d56Sopenharmony_ci then :func:`dataclass` *may* add an implicit :meth:`~object.__hash__` method. 1427db96d56Sopenharmony_ci Although not recommended, you can force :func:`dataclass` to create a 1437db96d56Sopenharmony_ci :meth:`~object.__hash__` method with ``unsafe_hash=True``. This might be the case 1447db96d56Sopenharmony_ci if your class is logically immutable but can nonetheless be mutated. 1457db96d56Sopenharmony_ci This is a specialized use case and should be considered carefully. 1467db96d56Sopenharmony_ci 1477db96d56Sopenharmony_ci Here are the rules governing implicit creation of a :meth:`~object.__hash__` 1487db96d56Sopenharmony_ci method. Note that you cannot both have an explicit :meth:`~object.__hash__` 1497db96d56Sopenharmony_ci method in your dataclass and set ``unsafe_hash=True``; this will result 1507db96d56Sopenharmony_ci in a :exc:`TypeError`. 1517db96d56Sopenharmony_ci 1527db96d56Sopenharmony_ci If ``eq`` and ``frozen`` are both true, by default :func:`dataclass` will 1537db96d56Sopenharmony_ci generate a :meth:`~object.__hash__` method for you. If ``eq`` is true and 1547db96d56Sopenharmony_ci ``frozen`` is false, :meth:`~object.__hash__` will be set to ``None``, marking it 1557db96d56Sopenharmony_ci unhashable (which it is, since it is mutable). If ``eq`` is false, 1567db96d56Sopenharmony_ci :meth:`~object.__hash__` will be left untouched meaning the :meth:`~object.__hash__` 1577db96d56Sopenharmony_ci method of the superclass will be used (if the superclass is 1587db96d56Sopenharmony_ci :class:`object`, this means it will fall back to id-based hashing). 1597db96d56Sopenharmony_ci 1607db96d56Sopenharmony_ci - ``frozen``: If true (the default is ``False``), assigning to fields will 1617db96d56Sopenharmony_ci generate an exception. This emulates read-only frozen instances. If 1627db96d56Sopenharmony_ci :meth:`~object.__setattr__` or :meth:`~object.__delattr__` is defined in the class, then 1637db96d56Sopenharmony_ci :exc:`TypeError` is raised. See the discussion below. 1647db96d56Sopenharmony_ci 1657db96d56Sopenharmony_ci - ``match_args``: If true (the default is ``True``), the 1667db96d56Sopenharmony_ci ``__match_args__`` tuple will be created from the list of 1677db96d56Sopenharmony_ci parameters to the generated :meth:`~object.__init__` method (even if 1687db96d56Sopenharmony_ci :meth:`~object.__init__` is not generated, see above). If false, or if 1697db96d56Sopenharmony_ci ``__match_args__`` is already defined in the class, then 1707db96d56Sopenharmony_ci ``__match_args__`` will not be generated. 1717db96d56Sopenharmony_ci 1727db96d56Sopenharmony_ci .. versionadded:: 3.10 1737db96d56Sopenharmony_ci 1747db96d56Sopenharmony_ci - ``kw_only``: If true (the default value is ``False``), then all 1757db96d56Sopenharmony_ci fields will be marked as keyword-only. If a field is marked as 1767db96d56Sopenharmony_ci keyword-only, then the only effect is that the :meth:`~object.__init__` 1777db96d56Sopenharmony_ci parameter generated from a keyword-only field must be specified 1787db96d56Sopenharmony_ci with a keyword when :meth:`~object.__init__` is called. There is no 1797db96d56Sopenharmony_ci effect on any other aspect of dataclasses. See the 1807db96d56Sopenharmony_ci :term:`parameter` glossary entry for details. Also see the 1817db96d56Sopenharmony_ci :const:`KW_ONLY` section. 1827db96d56Sopenharmony_ci 1837db96d56Sopenharmony_ci .. versionadded:: 3.10 1847db96d56Sopenharmony_ci 1857db96d56Sopenharmony_ci - ``slots``: If true (the default is ``False``), :attr:`~object.__slots__` attribute 1867db96d56Sopenharmony_ci will be generated and new class will be returned instead of the original one. 1877db96d56Sopenharmony_ci If :attr:`~object.__slots__` is already defined in the class, then :exc:`TypeError` 1887db96d56Sopenharmony_ci is raised. 1897db96d56Sopenharmony_ci 1907db96d56Sopenharmony_ci .. versionadded:: 3.10 1917db96d56Sopenharmony_ci 1927db96d56Sopenharmony_ci .. versionchanged:: 3.11 1937db96d56Sopenharmony_ci If a field name is already included in the ``__slots__`` 1947db96d56Sopenharmony_ci of a base class, it will not be included in the generated ``__slots__`` 1957db96d56Sopenharmony_ci to prevent :ref:`overriding them <datamodel-note-slots>`. 1967db96d56Sopenharmony_ci Therefore, do not use ``__slots__`` to retrieve the field names of a 1977db96d56Sopenharmony_ci dataclass. Use :func:`fields` instead. 1987db96d56Sopenharmony_ci To be able to determine inherited slots, 1997db96d56Sopenharmony_ci base class ``__slots__`` may be any iterable, but *not* an iterator. 2007db96d56Sopenharmony_ci 2017db96d56Sopenharmony_ci 2027db96d56Sopenharmony_ci - ``weakref_slot``: If true (the default is ``False``), add a slot 2037db96d56Sopenharmony_ci named "__weakref__", which is required to make an instance 2047db96d56Sopenharmony_ci weakref-able. It is an error to specify ``weakref_slot=True`` 2057db96d56Sopenharmony_ci without also specifying ``slots=True``. 2067db96d56Sopenharmony_ci 2077db96d56Sopenharmony_ci .. versionadded:: 3.11 2087db96d56Sopenharmony_ci 2097db96d56Sopenharmony_ci ``field``\s may optionally specify a default value, using normal 2107db96d56Sopenharmony_ci Python syntax:: 2117db96d56Sopenharmony_ci 2127db96d56Sopenharmony_ci @dataclass 2137db96d56Sopenharmony_ci class C: 2147db96d56Sopenharmony_ci a: int # 'a' has no default value 2157db96d56Sopenharmony_ci b: int = 0 # assign a default value for 'b' 2167db96d56Sopenharmony_ci 2177db96d56Sopenharmony_ci In this example, both ``a`` and ``b`` will be included in the added 2187db96d56Sopenharmony_ci :meth:`~object.__init__` method, which will be defined as:: 2197db96d56Sopenharmony_ci 2207db96d56Sopenharmony_ci def __init__(self, a: int, b: int = 0): 2217db96d56Sopenharmony_ci 2227db96d56Sopenharmony_ci :exc:`TypeError` will be raised if a field without a default value 2237db96d56Sopenharmony_ci follows a field with a default value. This is true whether this 2247db96d56Sopenharmony_ci occurs in a single class, or as a result of class inheritance. 2257db96d56Sopenharmony_ci 2267db96d56Sopenharmony_ci.. function:: field(*, default=MISSING, default_factory=MISSING, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=MISSING) 2277db96d56Sopenharmony_ci 2287db96d56Sopenharmony_ci For common and simple use cases, no other functionality is 2297db96d56Sopenharmony_ci required. There are, however, some dataclass features that 2307db96d56Sopenharmony_ci require additional per-field information. To satisfy this need for 2317db96d56Sopenharmony_ci additional information, you can replace the default field value 2327db96d56Sopenharmony_ci with a call to the provided :func:`field` function. For example:: 2337db96d56Sopenharmony_ci 2347db96d56Sopenharmony_ci @dataclass 2357db96d56Sopenharmony_ci class C: 2367db96d56Sopenharmony_ci mylist: list[int] = field(default_factory=list) 2377db96d56Sopenharmony_ci 2387db96d56Sopenharmony_ci c = C() 2397db96d56Sopenharmony_ci c.mylist += [1, 2, 3] 2407db96d56Sopenharmony_ci 2417db96d56Sopenharmony_ci As shown above, the :const:`MISSING` value is a sentinel object used to 2427db96d56Sopenharmony_ci detect if some parameters are provided by the user. This sentinel is 2437db96d56Sopenharmony_ci used because ``None`` is a valid value for some parameters with 2447db96d56Sopenharmony_ci a distinct meaning. No code should directly use the :const:`MISSING` value. 2457db96d56Sopenharmony_ci 2467db96d56Sopenharmony_ci The parameters to :func:`field` are: 2477db96d56Sopenharmony_ci 2487db96d56Sopenharmony_ci - ``default``: If provided, this will be the default value for this 2497db96d56Sopenharmony_ci field. This is needed because the :meth:`field` call itself 2507db96d56Sopenharmony_ci replaces the normal position of the default value. 2517db96d56Sopenharmony_ci 2527db96d56Sopenharmony_ci - ``default_factory``: If provided, it must be a zero-argument 2537db96d56Sopenharmony_ci callable that will be called when a default value is needed for 2547db96d56Sopenharmony_ci this field. Among other purposes, this can be used to specify 2557db96d56Sopenharmony_ci fields with mutable default values, as discussed below. It is an 2567db96d56Sopenharmony_ci error to specify both ``default`` and ``default_factory``. 2577db96d56Sopenharmony_ci 2587db96d56Sopenharmony_ci - ``init``: If true (the default), this field is included as a 2597db96d56Sopenharmony_ci parameter to the generated :meth:`~object.__init__` method. 2607db96d56Sopenharmony_ci 2617db96d56Sopenharmony_ci - ``repr``: If true (the default), this field is included in the 2627db96d56Sopenharmony_ci string returned by the generated :meth:`~object.__repr__` method. 2637db96d56Sopenharmony_ci 2647db96d56Sopenharmony_ci - ``hash``: This can be a bool or ``None``. If true, this field is 2657db96d56Sopenharmony_ci included in the generated :meth:`~object.__hash__` method. If ``None`` (the 2667db96d56Sopenharmony_ci default), use the value of ``compare``: this would normally be 2677db96d56Sopenharmony_ci the expected behavior. A field should be considered in the hash 2687db96d56Sopenharmony_ci if it's used for comparisons. Setting this value to anything 2697db96d56Sopenharmony_ci other than ``None`` is discouraged. 2707db96d56Sopenharmony_ci 2717db96d56Sopenharmony_ci One possible reason to set ``hash=False`` but ``compare=True`` 2727db96d56Sopenharmony_ci would be if a field is expensive to compute a hash value for, 2737db96d56Sopenharmony_ci that field is needed for equality testing, and there are other 2747db96d56Sopenharmony_ci fields that contribute to the type's hash value. Even if a field 2757db96d56Sopenharmony_ci is excluded from the hash, it will still be used for comparisons. 2767db96d56Sopenharmony_ci 2777db96d56Sopenharmony_ci - ``compare``: If true (the default), this field is included in the 2787db96d56Sopenharmony_ci generated equality and comparison methods (:meth:`~object.__eq__`, 2797db96d56Sopenharmony_ci :meth:`~object.__gt__`, et al.). 2807db96d56Sopenharmony_ci 2817db96d56Sopenharmony_ci - ``metadata``: This can be a mapping or None. None is treated as 2827db96d56Sopenharmony_ci an empty dict. This value is wrapped in 2837db96d56Sopenharmony_ci :func:`~types.MappingProxyType` to make it read-only, and exposed 2847db96d56Sopenharmony_ci on the :class:`Field` object. It is not used at all by Data 2857db96d56Sopenharmony_ci Classes, and is provided as a third-party extension mechanism. 2867db96d56Sopenharmony_ci Multiple third-parties can each have their own key, to use as a 2877db96d56Sopenharmony_ci namespace in the metadata. 2887db96d56Sopenharmony_ci 2897db96d56Sopenharmony_ci - ``kw_only``: If true, this field will be marked as keyword-only. 2907db96d56Sopenharmony_ci This is used when the generated :meth:`~object.__init__` method's 2917db96d56Sopenharmony_ci parameters are computed. 2927db96d56Sopenharmony_ci 2937db96d56Sopenharmony_ci .. versionadded:: 3.10 2947db96d56Sopenharmony_ci 2957db96d56Sopenharmony_ci If the default value of a field is specified by a call to 2967db96d56Sopenharmony_ci :func:`field()`, then the class attribute for this field will be 2977db96d56Sopenharmony_ci replaced by the specified ``default`` value. If no ``default`` is 2987db96d56Sopenharmony_ci provided, then the class attribute will be deleted. The intent is 2997db96d56Sopenharmony_ci that after the :func:`dataclass` decorator runs, the class 3007db96d56Sopenharmony_ci attributes will all contain the default values for the fields, just 3017db96d56Sopenharmony_ci as if the default value itself were specified. For example, 3027db96d56Sopenharmony_ci after:: 3037db96d56Sopenharmony_ci 3047db96d56Sopenharmony_ci @dataclass 3057db96d56Sopenharmony_ci class C: 3067db96d56Sopenharmony_ci x: int 3077db96d56Sopenharmony_ci y: int = field(repr=False) 3087db96d56Sopenharmony_ci z: int = field(repr=False, default=10) 3097db96d56Sopenharmony_ci t: int = 20 3107db96d56Sopenharmony_ci 3117db96d56Sopenharmony_ci The class attribute ``C.z`` will be ``10``, the class attribute 3127db96d56Sopenharmony_ci ``C.t`` will be ``20``, and the class attributes ``C.x`` and 3137db96d56Sopenharmony_ci ``C.y`` will not be set. 3147db96d56Sopenharmony_ci 3157db96d56Sopenharmony_ci.. class:: Field 3167db96d56Sopenharmony_ci 3177db96d56Sopenharmony_ci :class:`Field` objects describe each defined field. These objects 3187db96d56Sopenharmony_ci are created internally, and are returned by the :func:`fields` 3197db96d56Sopenharmony_ci module-level method (see below). Users should never instantiate a 3207db96d56Sopenharmony_ci :class:`Field` object directly. Its documented attributes are: 3217db96d56Sopenharmony_ci 3227db96d56Sopenharmony_ci - ``name``: The name of the field. 3237db96d56Sopenharmony_ci 3247db96d56Sopenharmony_ci - ``type``: The type of the field. 3257db96d56Sopenharmony_ci 3267db96d56Sopenharmony_ci - ``default``, ``default_factory``, ``init``, ``repr``, ``hash``, 3277db96d56Sopenharmony_ci ``compare``, ``metadata``, and ``kw_only`` have the identical 3287db96d56Sopenharmony_ci meaning and values as they do in the :func:`field` function. 3297db96d56Sopenharmony_ci 3307db96d56Sopenharmony_ci Other attributes may exist, but they are private and must not be 3317db96d56Sopenharmony_ci inspected or relied on. 3327db96d56Sopenharmony_ci 3337db96d56Sopenharmony_ci.. function:: fields(class_or_instance) 3347db96d56Sopenharmony_ci 3357db96d56Sopenharmony_ci Returns a tuple of :class:`Field` objects that define the fields for this 3367db96d56Sopenharmony_ci dataclass. Accepts either a dataclass, or an instance of a dataclass. 3377db96d56Sopenharmony_ci Raises :exc:`TypeError` if not passed a dataclass or instance of one. 3387db96d56Sopenharmony_ci Does not return pseudo-fields which are ``ClassVar`` or ``InitVar``. 3397db96d56Sopenharmony_ci 3407db96d56Sopenharmony_ci.. function:: asdict(obj, *, dict_factory=dict) 3417db96d56Sopenharmony_ci 3427db96d56Sopenharmony_ci Converts the dataclass ``obj`` to a dict (by using the 3437db96d56Sopenharmony_ci factory function ``dict_factory``). Each dataclass is converted 3447db96d56Sopenharmony_ci to a dict of its fields, as ``name: value`` pairs. dataclasses, dicts, 3457db96d56Sopenharmony_ci lists, and tuples are recursed into. Other objects are copied with 3467db96d56Sopenharmony_ci :func:`copy.deepcopy`. 3477db96d56Sopenharmony_ci 3487db96d56Sopenharmony_ci Example of using :func:`asdict` on nested dataclasses:: 3497db96d56Sopenharmony_ci 3507db96d56Sopenharmony_ci @dataclass 3517db96d56Sopenharmony_ci class Point: 3527db96d56Sopenharmony_ci x: int 3537db96d56Sopenharmony_ci y: int 3547db96d56Sopenharmony_ci 3557db96d56Sopenharmony_ci @dataclass 3567db96d56Sopenharmony_ci class C: 3577db96d56Sopenharmony_ci mylist: list[Point] 3587db96d56Sopenharmony_ci 3597db96d56Sopenharmony_ci p = Point(10, 20) 3607db96d56Sopenharmony_ci assert asdict(p) == {'x': 10, 'y': 20} 3617db96d56Sopenharmony_ci 3627db96d56Sopenharmony_ci c = C([Point(0, 0), Point(10, 4)]) 3637db96d56Sopenharmony_ci assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]} 3647db96d56Sopenharmony_ci 3657db96d56Sopenharmony_ci To create a shallow copy, the following workaround may be used:: 3667db96d56Sopenharmony_ci 3677db96d56Sopenharmony_ci dict((field.name, getattr(obj, field.name)) for field in fields(obj)) 3687db96d56Sopenharmony_ci 3697db96d56Sopenharmony_ci :func:`asdict` raises :exc:`TypeError` if ``obj`` is not a dataclass 3707db96d56Sopenharmony_ci instance. 3717db96d56Sopenharmony_ci 3727db96d56Sopenharmony_ci.. function:: astuple(obj, *, tuple_factory=tuple) 3737db96d56Sopenharmony_ci 3747db96d56Sopenharmony_ci Converts the dataclass ``obj`` to a tuple (by using the 3757db96d56Sopenharmony_ci factory function ``tuple_factory``). Each dataclass is converted 3767db96d56Sopenharmony_ci to a tuple of its field values. dataclasses, dicts, lists, and 3777db96d56Sopenharmony_ci tuples are recursed into. Other objects are copied with 3787db96d56Sopenharmony_ci :func:`copy.deepcopy`. 3797db96d56Sopenharmony_ci 3807db96d56Sopenharmony_ci Continuing from the previous example:: 3817db96d56Sopenharmony_ci 3827db96d56Sopenharmony_ci assert astuple(p) == (10, 20) 3837db96d56Sopenharmony_ci assert astuple(c) == ([(0, 0), (10, 4)],) 3847db96d56Sopenharmony_ci 3857db96d56Sopenharmony_ci To create a shallow copy, the following workaround may be used:: 3867db96d56Sopenharmony_ci 3877db96d56Sopenharmony_ci tuple(getattr(obj, field.name) for field in dataclasses.fields(obj)) 3887db96d56Sopenharmony_ci 3897db96d56Sopenharmony_ci :func:`astuple` raises :exc:`TypeError` if ``obj`` is not a dataclass 3907db96d56Sopenharmony_ci instance. 3917db96d56Sopenharmony_ci 3927db96d56Sopenharmony_ci.. 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) 3937db96d56Sopenharmony_ci 3947db96d56Sopenharmony_ci Creates a new dataclass with name ``cls_name``, fields as defined 3957db96d56Sopenharmony_ci in ``fields``, base classes as given in ``bases``, and initialized 3967db96d56Sopenharmony_ci with a namespace as given in ``namespace``. ``fields`` is an 3977db96d56Sopenharmony_ci iterable whose elements are each either ``name``, ``(name, type)``, 3987db96d56Sopenharmony_ci or ``(name, type, Field)``. If just ``name`` is supplied, 3997db96d56Sopenharmony_ci ``typing.Any`` is used for ``type``. The values of ``init``, 4007db96d56Sopenharmony_ci ``repr``, ``eq``, ``order``, ``unsafe_hash``, ``frozen``, 4017db96d56Sopenharmony_ci ``match_args``, ``kw_only``, ``slots``, and ``weakref_slot`` have 4027db96d56Sopenharmony_ci the same meaning as they do in :func:`dataclass`. 4037db96d56Sopenharmony_ci 4047db96d56Sopenharmony_ci This function is not strictly required, because any Python 4057db96d56Sopenharmony_ci mechanism for creating a new class with ``__annotations__`` can 4067db96d56Sopenharmony_ci then apply the :func:`dataclass` function to convert that class to 4077db96d56Sopenharmony_ci a dataclass. This function is provided as a convenience. For 4087db96d56Sopenharmony_ci example:: 4097db96d56Sopenharmony_ci 4107db96d56Sopenharmony_ci C = make_dataclass('C', 4117db96d56Sopenharmony_ci [('x', int), 4127db96d56Sopenharmony_ci 'y', 4137db96d56Sopenharmony_ci ('z', int, field(default=5))], 4147db96d56Sopenharmony_ci namespace={'add_one': lambda self: self.x + 1}) 4157db96d56Sopenharmony_ci 4167db96d56Sopenharmony_ci Is equivalent to:: 4177db96d56Sopenharmony_ci 4187db96d56Sopenharmony_ci @dataclass 4197db96d56Sopenharmony_ci class C: 4207db96d56Sopenharmony_ci x: int 4217db96d56Sopenharmony_ci y: 'typing.Any' 4227db96d56Sopenharmony_ci z: int = 5 4237db96d56Sopenharmony_ci 4247db96d56Sopenharmony_ci def add_one(self): 4257db96d56Sopenharmony_ci return self.x + 1 4267db96d56Sopenharmony_ci 4277db96d56Sopenharmony_ci.. function:: replace(obj, /, **changes) 4287db96d56Sopenharmony_ci 4297db96d56Sopenharmony_ci Creates a new object of the same type as ``obj``, replacing 4307db96d56Sopenharmony_ci fields with values from ``changes``. If ``obj`` is not a Data 4317db96d56Sopenharmony_ci Class, raises :exc:`TypeError`. If values in ``changes`` do not 4327db96d56Sopenharmony_ci specify fields, raises :exc:`TypeError`. 4337db96d56Sopenharmony_ci 4347db96d56Sopenharmony_ci The newly returned object is created by calling the :meth:`~object.__init__` 4357db96d56Sopenharmony_ci method of the dataclass. This ensures that 4367db96d56Sopenharmony_ci :ref:`__post_init__ <post-init-processing>`, if present, is also called. 4377db96d56Sopenharmony_ci 4387db96d56Sopenharmony_ci Init-only variables without default values, if any exist, must be 4397db96d56Sopenharmony_ci specified on the call to :func:`replace` so that they can be passed to 4407db96d56Sopenharmony_ci :meth:`~object.__init__` and :ref:`__post_init__ <post-init-processing>`. 4417db96d56Sopenharmony_ci 4427db96d56Sopenharmony_ci It is an error for ``changes`` to contain any fields that are 4437db96d56Sopenharmony_ci defined as having ``init=False``. A :exc:`ValueError` will be raised 4447db96d56Sopenharmony_ci in this case. 4457db96d56Sopenharmony_ci 4467db96d56Sopenharmony_ci Be forewarned about how ``init=False`` fields work during a call to 4477db96d56Sopenharmony_ci :func:`replace`. They are not copied from the source object, but 4487db96d56Sopenharmony_ci rather are initialized in :ref:`__post_init__ <post-init-processing>`, if they're 4497db96d56Sopenharmony_ci initialized at all. It is expected that ``init=False`` fields will 4507db96d56Sopenharmony_ci be rarely and judiciously used. If they are used, it might be wise 4517db96d56Sopenharmony_ci to have alternate class constructors, or perhaps a custom 4527db96d56Sopenharmony_ci ``replace()`` (or similarly named) method which handles instance 4537db96d56Sopenharmony_ci copying. 4547db96d56Sopenharmony_ci 4557db96d56Sopenharmony_ci.. function:: is_dataclass(obj) 4567db96d56Sopenharmony_ci 4577db96d56Sopenharmony_ci Return ``True`` if its parameter is a dataclass or an instance of one, 4587db96d56Sopenharmony_ci otherwise return ``False``. 4597db96d56Sopenharmony_ci 4607db96d56Sopenharmony_ci If you need to know if a class is an instance of a dataclass (and 4617db96d56Sopenharmony_ci not a dataclass itself), then add a further check for ``not 4627db96d56Sopenharmony_ci isinstance(obj, type)``:: 4637db96d56Sopenharmony_ci 4647db96d56Sopenharmony_ci def is_dataclass_instance(obj): 4657db96d56Sopenharmony_ci return is_dataclass(obj) and not isinstance(obj, type) 4667db96d56Sopenharmony_ci 4677db96d56Sopenharmony_ci.. data:: MISSING 4687db96d56Sopenharmony_ci 4697db96d56Sopenharmony_ci A sentinel value signifying a missing default or default_factory. 4707db96d56Sopenharmony_ci 4717db96d56Sopenharmony_ci.. data:: KW_ONLY 4727db96d56Sopenharmony_ci 4737db96d56Sopenharmony_ci A sentinel value used as a type annotation. Any fields after a 4747db96d56Sopenharmony_ci pseudo-field with the type of :const:`KW_ONLY` are marked as 4757db96d56Sopenharmony_ci keyword-only fields. Note that a pseudo-field of type 4767db96d56Sopenharmony_ci :const:`KW_ONLY` is otherwise completely ignored. This includes the 4777db96d56Sopenharmony_ci name of such a field. By convention, a name of ``_`` is used for a 4787db96d56Sopenharmony_ci :const:`KW_ONLY` field. Keyword-only fields signify 4797db96d56Sopenharmony_ci :meth:`~object.__init__` parameters that must be specified as keywords when 4807db96d56Sopenharmony_ci the class is instantiated. 4817db96d56Sopenharmony_ci 4827db96d56Sopenharmony_ci In this example, the fields ``y`` and ``z`` will be marked as keyword-only fields:: 4837db96d56Sopenharmony_ci 4847db96d56Sopenharmony_ci @dataclass 4857db96d56Sopenharmony_ci class Point: 4867db96d56Sopenharmony_ci x: float 4877db96d56Sopenharmony_ci _: KW_ONLY 4887db96d56Sopenharmony_ci y: float 4897db96d56Sopenharmony_ci z: float 4907db96d56Sopenharmony_ci 4917db96d56Sopenharmony_ci p = Point(0, y=1.5, z=2.0) 4927db96d56Sopenharmony_ci 4937db96d56Sopenharmony_ci In a single dataclass, it is an error to specify more than one 4947db96d56Sopenharmony_ci field whose type is :const:`KW_ONLY`. 4957db96d56Sopenharmony_ci 4967db96d56Sopenharmony_ci .. versionadded:: 3.10 4977db96d56Sopenharmony_ci 4987db96d56Sopenharmony_ci.. exception:: FrozenInstanceError 4997db96d56Sopenharmony_ci 5007db96d56Sopenharmony_ci Raised when an implicitly defined :meth:`~object.__setattr__` or 5017db96d56Sopenharmony_ci :meth:`~object.__delattr__` is called on a dataclass which was defined with 5027db96d56Sopenharmony_ci ``frozen=True``. It is a subclass of :exc:`AttributeError`. 5037db96d56Sopenharmony_ci 5047db96d56Sopenharmony_ci.. _post-init-processing: 5057db96d56Sopenharmony_ci 5067db96d56Sopenharmony_ciPost-init processing 5077db96d56Sopenharmony_ci-------------------- 5087db96d56Sopenharmony_ci 5097db96d56Sopenharmony_ciThe generated :meth:`~object.__init__` code will call a method named 5107db96d56Sopenharmony_ci:meth:`!__post_init__`, if :meth:`!__post_init__` is defined on the 5117db96d56Sopenharmony_ciclass. It will normally be called as ``self.__post_init__()``. 5127db96d56Sopenharmony_ciHowever, if any ``InitVar`` fields are defined, they will also be 5137db96d56Sopenharmony_cipassed to :meth:`!__post_init__` in the order they were defined in the 5147db96d56Sopenharmony_ciclass. If no :meth:`~object.__init__` method is generated, then 5157db96d56Sopenharmony_ci:meth:`!__post_init__` will not automatically be called. 5167db96d56Sopenharmony_ci 5177db96d56Sopenharmony_ciAmong other uses, this allows for initializing field values that 5187db96d56Sopenharmony_cidepend on one or more other fields. For example:: 5197db96d56Sopenharmony_ci 5207db96d56Sopenharmony_ci @dataclass 5217db96d56Sopenharmony_ci class C: 5227db96d56Sopenharmony_ci a: float 5237db96d56Sopenharmony_ci b: float 5247db96d56Sopenharmony_ci c: float = field(init=False) 5257db96d56Sopenharmony_ci 5267db96d56Sopenharmony_ci def __post_init__(self): 5277db96d56Sopenharmony_ci self.c = self.a + self.b 5287db96d56Sopenharmony_ci 5297db96d56Sopenharmony_ciThe :meth:`~object.__init__` method generated by :func:`dataclass` does not call base 5307db96d56Sopenharmony_ciclass :meth:`~object.__init__` methods. If the base class has an :meth:`~object.__init__` method 5317db96d56Sopenharmony_cithat has to be called, it is common to call this method in a 5327db96d56Sopenharmony_ci:meth:`!__post_init__` method:: 5337db96d56Sopenharmony_ci 5347db96d56Sopenharmony_ci @dataclass 5357db96d56Sopenharmony_ci class Rectangle: 5367db96d56Sopenharmony_ci height: float 5377db96d56Sopenharmony_ci width: float 5387db96d56Sopenharmony_ci 5397db96d56Sopenharmony_ci @dataclass 5407db96d56Sopenharmony_ci class Square(Rectangle): 5417db96d56Sopenharmony_ci side: float 5427db96d56Sopenharmony_ci 5437db96d56Sopenharmony_ci def __post_init__(self): 5447db96d56Sopenharmony_ci super().__init__(self.side, self.side) 5457db96d56Sopenharmony_ci 5467db96d56Sopenharmony_ciNote, however, that in general the dataclass-generated :meth:`~object.__init__` methods 5477db96d56Sopenharmony_cidon't need to be called, since the derived dataclass will take care of 5487db96d56Sopenharmony_ciinitializing all fields of any base class that is a dataclass itself. 5497db96d56Sopenharmony_ci 5507db96d56Sopenharmony_ciSee the section below on init-only variables for ways to pass 5517db96d56Sopenharmony_ciparameters to :meth:`!__post_init__`. Also see the warning about how 5527db96d56Sopenharmony_ci:func:`replace` handles ``init=False`` fields. 5537db96d56Sopenharmony_ci 5547db96d56Sopenharmony_ciClass variables 5557db96d56Sopenharmony_ci--------------- 5567db96d56Sopenharmony_ci 5577db96d56Sopenharmony_ciOne of the few places where :func:`dataclass` actually inspects the type 5587db96d56Sopenharmony_ciof a field is to determine if a field is a class variable as defined 5597db96d56Sopenharmony_ciin :pep:`526`. It does this by checking if the type of the field is 5607db96d56Sopenharmony_ci``typing.ClassVar``. If a field is a ``ClassVar``, it is excluded 5617db96d56Sopenharmony_cifrom consideration as a field and is ignored by the dataclass 5627db96d56Sopenharmony_cimechanisms. Such ``ClassVar`` pseudo-fields are not returned by the 5637db96d56Sopenharmony_cimodule-level :func:`fields` function. 5647db96d56Sopenharmony_ci 5657db96d56Sopenharmony_ciInit-only variables 5667db96d56Sopenharmony_ci------------------- 5677db96d56Sopenharmony_ci 5687db96d56Sopenharmony_ciAnother place where :func:`dataclass` inspects a type annotation is to 5697db96d56Sopenharmony_cidetermine if a field is an init-only variable. It does this by seeing 5707db96d56Sopenharmony_ciif the type of a field is of type ``dataclasses.InitVar``. If a field 5717db96d56Sopenharmony_ciis an ``InitVar``, it is considered a pseudo-field called an init-only 5727db96d56Sopenharmony_cifield. As it is not a true field, it is not returned by the 5737db96d56Sopenharmony_cimodule-level :func:`fields` function. Init-only fields are added as 5747db96d56Sopenharmony_ciparameters to the generated :meth:`~object.__init__` method, and are passed to 5757db96d56Sopenharmony_cithe optional :ref:`__post_init__ <post-init-processing>` method. They are not otherwise used 5767db96d56Sopenharmony_ciby dataclasses. 5777db96d56Sopenharmony_ci 5787db96d56Sopenharmony_ciFor example, suppose a field will be initialized from a database, if a 5797db96d56Sopenharmony_civalue is not provided when creating the class:: 5807db96d56Sopenharmony_ci 5817db96d56Sopenharmony_ci @dataclass 5827db96d56Sopenharmony_ci class C: 5837db96d56Sopenharmony_ci i: int 5847db96d56Sopenharmony_ci j: int | None = None 5857db96d56Sopenharmony_ci database: InitVar[DatabaseType | None] = None 5867db96d56Sopenharmony_ci 5877db96d56Sopenharmony_ci def __post_init__(self, database): 5887db96d56Sopenharmony_ci if self.j is None and database is not None: 5897db96d56Sopenharmony_ci self.j = database.lookup('j') 5907db96d56Sopenharmony_ci 5917db96d56Sopenharmony_ci c = C(10, database=my_database) 5927db96d56Sopenharmony_ci 5937db96d56Sopenharmony_ciIn this case, :func:`fields` will return :class:`Field` objects for ``i`` and 5947db96d56Sopenharmony_ci``j``, but not for ``database``. 5957db96d56Sopenharmony_ci 5967db96d56Sopenharmony_ciFrozen instances 5977db96d56Sopenharmony_ci---------------- 5987db96d56Sopenharmony_ci 5997db96d56Sopenharmony_ciIt is not possible to create truly immutable Python objects. However, 6007db96d56Sopenharmony_ciby passing ``frozen=True`` to the :meth:`dataclass` decorator you can 6017db96d56Sopenharmony_ciemulate immutability. In that case, dataclasses will add 6027db96d56Sopenharmony_ci:meth:`~object.__setattr__` and :meth:`~object.__delattr__` methods to the class. These 6037db96d56Sopenharmony_cimethods will raise a :exc:`FrozenInstanceError` when invoked. 6047db96d56Sopenharmony_ci 6057db96d56Sopenharmony_ciThere is a tiny performance penalty when using ``frozen=True``: 6067db96d56Sopenharmony_ci:meth:`~object.__init__` cannot use simple assignment to initialize fields, and 6077db96d56Sopenharmony_cimust use :meth:`~object.__setattr__`. 6087db96d56Sopenharmony_ci 6097db96d56Sopenharmony_ciInheritance 6107db96d56Sopenharmony_ci----------- 6117db96d56Sopenharmony_ci 6127db96d56Sopenharmony_ciWhen the dataclass is being created by the :meth:`dataclass` decorator, 6137db96d56Sopenharmony_ciit looks through all of the class's base classes in reverse MRO (that 6147db96d56Sopenharmony_ciis, starting at :class:`object`) and, for each dataclass that it finds, 6157db96d56Sopenharmony_ciadds the fields from that base class to an ordered mapping of fields. 6167db96d56Sopenharmony_ciAfter all of the base class fields are added, it adds its own fields 6177db96d56Sopenharmony_cito the ordered mapping. All of the generated methods will use this 6187db96d56Sopenharmony_cicombined, calculated ordered mapping of fields. Because the fields 6197db96d56Sopenharmony_ciare in insertion order, derived classes override base classes. An 6207db96d56Sopenharmony_ciexample:: 6217db96d56Sopenharmony_ci 6227db96d56Sopenharmony_ci @dataclass 6237db96d56Sopenharmony_ci class Base: 6247db96d56Sopenharmony_ci x: Any = 15.0 6257db96d56Sopenharmony_ci y: int = 0 6267db96d56Sopenharmony_ci 6277db96d56Sopenharmony_ci @dataclass 6287db96d56Sopenharmony_ci class C(Base): 6297db96d56Sopenharmony_ci z: int = 10 6307db96d56Sopenharmony_ci x: int = 15 6317db96d56Sopenharmony_ci 6327db96d56Sopenharmony_ciThe final list of fields is, in order, ``x``, ``y``, ``z``. The final 6337db96d56Sopenharmony_citype of ``x`` is ``int``, as specified in class ``C``. 6347db96d56Sopenharmony_ci 6357db96d56Sopenharmony_ciThe generated :meth:`~object.__init__` method for ``C`` will look like:: 6367db96d56Sopenharmony_ci 6377db96d56Sopenharmony_ci def __init__(self, x: int = 15, y: int = 0, z: int = 10): 6387db96d56Sopenharmony_ci 6397db96d56Sopenharmony_ciRe-ordering of keyword-only parameters in :meth:`~object.__init__` 6407db96d56Sopenharmony_ci------------------------------------------------------------------ 6417db96d56Sopenharmony_ci 6427db96d56Sopenharmony_ciAfter the parameters needed for :meth:`~object.__init__` are computed, any 6437db96d56Sopenharmony_cikeyword-only parameters are moved to come after all regular 6447db96d56Sopenharmony_ci(non-keyword-only) parameters. This is a requirement of how 6457db96d56Sopenharmony_cikeyword-only parameters are implemented in Python: they must come 6467db96d56Sopenharmony_ciafter non-keyword-only parameters. 6477db96d56Sopenharmony_ci 6487db96d56Sopenharmony_ciIn this example, ``Base.y``, ``Base.w``, and ``D.t`` are keyword-only 6497db96d56Sopenharmony_cifields, and ``Base.x`` and ``D.z`` are regular fields:: 6507db96d56Sopenharmony_ci 6517db96d56Sopenharmony_ci @dataclass 6527db96d56Sopenharmony_ci class Base: 6537db96d56Sopenharmony_ci x: Any = 15.0 6547db96d56Sopenharmony_ci _: KW_ONLY 6557db96d56Sopenharmony_ci y: int = 0 6567db96d56Sopenharmony_ci w: int = 1 6577db96d56Sopenharmony_ci 6587db96d56Sopenharmony_ci @dataclass 6597db96d56Sopenharmony_ci class D(Base): 6607db96d56Sopenharmony_ci z: int = 10 6617db96d56Sopenharmony_ci t: int = field(kw_only=True, default=0) 6627db96d56Sopenharmony_ci 6637db96d56Sopenharmony_ciThe generated :meth:`~object.__init__` method for ``D`` will look like:: 6647db96d56Sopenharmony_ci 6657db96d56Sopenharmony_ci def __init__(self, x: Any = 15.0, z: int = 10, *, y: int = 0, w: int = 1, t: int = 0): 6667db96d56Sopenharmony_ci 6677db96d56Sopenharmony_ciNote that the parameters have been re-ordered from how they appear in 6687db96d56Sopenharmony_cithe list of fields: parameters derived from regular fields are 6697db96d56Sopenharmony_cifollowed by parameters derived from keyword-only fields. 6707db96d56Sopenharmony_ci 6717db96d56Sopenharmony_ciThe relative ordering of keyword-only parameters is maintained in the 6727db96d56Sopenharmony_cire-ordered :meth:`~object.__init__` parameter list. 6737db96d56Sopenharmony_ci 6747db96d56Sopenharmony_ci 6757db96d56Sopenharmony_ciDefault factory functions 6767db96d56Sopenharmony_ci------------------------- 6777db96d56Sopenharmony_ci 6787db96d56Sopenharmony_ciIf a :func:`field` specifies a ``default_factory``, it is called with 6797db96d56Sopenharmony_cizero arguments when a default value for the field is needed. For 6807db96d56Sopenharmony_ciexample, to create a new instance of a list, use:: 6817db96d56Sopenharmony_ci 6827db96d56Sopenharmony_ci mylist: list = field(default_factory=list) 6837db96d56Sopenharmony_ci 6847db96d56Sopenharmony_ciIf a field is excluded from :meth:`~object.__init__` (using ``init=False``) 6857db96d56Sopenharmony_ciand the field also specifies ``default_factory``, then the default 6867db96d56Sopenharmony_cifactory function will always be called from the generated 6877db96d56Sopenharmony_ci:meth:`~object.__init__` function. This happens because there is no other 6887db96d56Sopenharmony_ciway to give the field an initial value. 6897db96d56Sopenharmony_ci 6907db96d56Sopenharmony_ciMutable default values 6917db96d56Sopenharmony_ci---------------------- 6927db96d56Sopenharmony_ci 6937db96d56Sopenharmony_ciPython stores default member variable values in class attributes. 6947db96d56Sopenharmony_ciConsider this example, not using dataclasses:: 6957db96d56Sopenharmony_ci 6967db96d56Sopenharmony_ci class C: 6977db96d56Sopenharmony_ci x = [] 6987db96d56Sopenharmony_ci def add(self, element): 6997db96d56Sopenharmony_ci self.x.append(element) 7007db96d56Sopenharmony_ci 7017db96d56Sopenharmony_ci o1 = C() 7027db96d56Sopenharmony_ci o2 = C() 7037db96d56Sopenharmony_ci o1.add(1) 7047db96d56Sopenharmony_ci o2.add(2) 7057db96d56Sopenharmony_ci assert o1.x == [1, 2] 7067db96d56Sopenharmony_ci assert o1.x is o2.x 7077db96d56Sopenharmony_ci 7087db96d56Sopenharmony_ciNote that the two instances of class ``C`` share the same class 7097db96d56Sopenharmony_civariable ``x``, as expected. 7107db96d56Sopenharmony_ci 7117db96d56Sopenharmony_ciUsing dataclasses, *if* this code was valid:: 7127db96d56Sopenharmony_ci 7137db96d56Sopenharmony_ci @dataclass 7147db96d56Sopenharmony_ci class D: 7157db96d56Sopenharmony_ci x: list = [] # This code raises ValueError 7167db96d56Sopenharmony_ci def add(self, element): 7177db96d56Sopenharmony_ci self.x += element 7187db96d56Sopenharmony_ci 7197db96d56Sopenharmony_ciit would generate code similar to:: 7207db96d56Sopenharmony_ci 7217db96d56Sopenharmony_ci class D: 7227db96d56Sopenharmony_ci x = [] 7237db96d56Sopenharmony_ci def __init__(self, x=x): 7247db96d56Sopenharmony_ci self.x = x 7257db96d56Sopenharmony_ci def add(self, element): 7267db96d56Sopenharmony_ci self.x += element 7277db96d56Sopenharmony_ci 7287db96d56Sopenharmony_ci assert D().x is D().x 7297db96d56Sopenharmony_ci 7307db96d56Sopenharmony_ciThis has the same issue as the original example using class ``C``. 7317db96d56Sopenharmony_ciThat is, two instances of class ``D`` that do not specify a value 7327db96d56Sopenharmony_cifor ``x`` when creating a class instance will share the same copy 7337db96d56Sopenharmony_ciof ``x``. Because dataclasses just use normal Python class 7347db96d56Sopenharmony_cicreation they also share this behavior. There is no general way 7357db96d56Sopenharmony_cifor Data Classes to detect this condition. Instead, the 7367db96d56Sopenharmony_ci:func:`dataclass` decorator will raise a :exc:`TypeError` if it 7377db96d56Sopenharmony_cidetects an unhashable default parameter. The assumption is that if 7387db96d56Sopenharmony_cia value is unhashable, it is mutable. This is a partial solution, 7397db96d56Sopenharmony_cibut it does protect against many common errors. 7407db96d56Sopenharmony_ci 7417db96d56Sopenharmony_ciUsing default factory functions is a way to create new instances of 7427db96d56Sopenharmony_cimutable types as default values for fields:: 7437db96d56Sopenharmony_ci 7447db96d56Sopenharmony_ci @dataclass 7457db96d56Sopenharmony_ci class D: 7467db96d56Sopenharmony_ci x: list = field(default_factory=list) 7477db96d56Sopenharmony_ci 7487db96d56Sopenharmony_ci assert D().x is not D().x 7497db96d56Sopenharmony_ci 7507db96d56Sopenharmony_ci.. versionchanged:: 3.11 7517db96d56Sopenharmony_ci Instead of looking for and disallowing objects of type ``list``, 7527db96d56Sopenharmony_ci ``dict``, or ``set``, unhashable objects are now not allowed as 7537db96d56Sopenharmony_ci default values. Unhashability is used to approximate 7547db96d56Sopenharmony_ci mutability. 7557db96d56Sopenharmony_ci 7567db96d56Sopenharmony_ciDescriptor-typed fields 7577db96d56Sopenharmony_ci----------------------- 7587db96d56Sopenharmony_ci 7597db96d56Sopenharmony_ciFields that are assigned :ref:`descriptor objects <descriptors>` as their 7607db96d56Sopenharmony_cidefault value have the following special behaviors: 7617db96d56Sopenharmony_ci 7627db96d56Sopenharmony_ci* The value for the field passed to the dataclass's ``__init__`` method is 7637db96d56Sopenharmony_ci passed to the descriptor's ``__set__`` method rather than overwriting the 7647db96d56Sopenharmony_ci descriptor object. 7657db96d56Sopenharmony_ci* Similarly, when getting or setting the field, the descriptor's 7667db96d56Sopenharmony_ci ``__get__`` or ``__set__`` method is called rather than returning or 7677db96d56Sopenharmony_ci overwriting the descriptor object. 7687db96d56Sopenharmony_ci* To determine whether a field contains a default value, ``dataclasses`` 7697db96d56Sopenharmony_ci will call the descriptor's ``__get__`` method using its class access 7707db96d56Sopenharmony_ci form (i.e. ``descriptor.__get__(obj=None, type=cls)``. If the 7717db96d56Sopenharmony_ci descriptor returns a value in this case, it will be used as the 7727db96d56Sopenharmony_ci field's default. On the other hand, if the descriptor raises 7737db96d56Sopenharmony_ci :exc:`AttributeError` in this situation, no default value will be 7747db96d56Sopenharmony_ci provided for the field. 7757db96d56Sopenharmony_ci 7767db96d56Sopenharmony_ci:: 7777db96d56Sopenharmony_ci 7787db96d56Sopenharmony_ci class IntConversionDescriptor: 7797db96d56Sopenharmony_ci def __init__(self, *, default): 7807db96d56Sopenharmony_ci self._default = default 7817db96d56Sopenharmony_ci 7827db96d56Sopenharmony_ci def __set_name__(self, owner, name): 7837db96d56Sopenharmony_ci self._name = "_" + name 7847db96d56Sopenharmony_ci 7857db96d56Sopenharmony_ci def __get__(self, obj, type): 7867db96d56Sopenharmony_ci if obj is None: 7877db96d56Sopenharmony_ci return self._default 7887db96d56Sopenharmony_ci 7897db96d56Sopenharmony_ci return getattr(obj, self._name, self._default) 7907db96d56Sopenharmony_ci 7917db96d56Sopenharmony_ci def __set__(self, obj, value): 7927db96d56Sopenharmony_ci setattr(obj, self._name, int(value)) 7937db96d56Sopenharmony_ci 7947db96d56Sopenharmony_ci @dataclass 7957db96d56Sopenharmony_ci class InventoryItem: 7967db96d56Sopenharmony_ci quantity_on_hand: IntConversionDescriptor = IntConversionDescriptor(default=100) 7977db96d56Sopenharmony_ci 7987db96d56Sopenharmony_ci i = InventoryItem() 7997db96d56Sopenharmony_ci print(i.quantity_on_hand) # 100 8007db96d56Sopenharmony_ci i.quantity_on_hand = 2.5 # calls __set__ with 2.5 8017db96d56Sopenharmony_ci print(i.quantity_on_hand) # 2 8027db96d56Sopenharmony_ci 8037db96d56Sopenharmony_ciNote that if a field is annotated with a descriptor type, but is not assigned 8047db96d56Sopenharmony_cia descriptor object as its default value, the field will act like a normal 8057db96d56Sopenharmony_cifield. 806