diff options
| author | Craig Jennings <c@cjennings.net> | 2024-04-07 13:41:34 -0500 |
|---|---|---|
| committer | Craig Jennings <c@cjennings.net> | 2024-04-07 13:41:34 -0500 |
| commit | 754bbf7a25a8dda49b5d08ef0d0443bbf5af0e36 (patch) | |
| tree | f1190704f78f04a2b0b4c977d20fe96a828377f1 /devdocs/python~3.12/library%2Fdataclasses.html | |
new repository
Diffstat (limited to 'devdocs/python~3.12/library%2Fdataclasses.html')
| -rw-r--r-- | devdocs/python~3.12/library%2Fdataclasses.html | 258 |
1 files changed, 258 insertions, 0 deletions
diff --git a/devdocs/python~3.12/library%2Fdataclasses.html b/devdocs/python~3.12/library%2Fdataclasses.html new file mode 100644 index 00000000..117fccd4 --- /dev/null +++ b/devdocs/python~3.12/library%2Fdataclasses.html @@ -0,0 +1,258 @@ + <span id="dataclasses-data-classes"></span><h1>dataclasses — Data Classes</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/dataclasses.py">Lib/dataclasses.py</a></p> <p>This module provides a decorator and functions for automatically adding generated <a class="reference internal" href="../glossary#term-special-method"><span class="xref std std-term">special method</span></a>s such as <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> and <a class="reference internal" href="../reference/datamodel#object.__repr__" title="object.__repr__"><code>__repr__()</code></a> to user-defined classes. It was originally described in <span class="target" id="index-0"></span><a class="pep reference external" href="https://peps.python.org/pep-0557/"><strong>PEP 557</strong></a>.</p> <p>The member variables to use in these generated methods are defined using <span class="target" id="index-1"></span><a class="pep reference external" href="https://peps.python.org/pep-0526/"><strong>PEP 526</strong></a> type annotations. For example, this code:</p> <pre data-language="python">from dataclasses import dataclass + +@dataclass +class InventoryItem: + """Class for keeping track of an item in inventory.""" + name: str + unit_price: float + quantity_on_hand: int = 0 + + def total_cost(self) -> float: + return self.unit_price * self.quantity_on_hand +</pre> <p>will add, among other things, a <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> that looks like:</p> <pre data-language="python">def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0): + self.name = name + self.unit_price = unit_price + self.quantity_on_hand = quantity_on_hand +</pre> <p>Note that this method is automatically added to the class: it is not directly specified in the <code>InventoryItem</code> definition shown above.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.7.</span></p> </div> <section id="module-contents"> <h2>Module contents</h2> <dl class="py function"> <dt class="sig sig-object py" id="dataclasses.dataclass"> +<code>@dataclasses.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)</code> </dt> <dd> +<p>This function is a <a class="reference internal" href="../glossary#term-decorator"><span class="xref std std-term">decorator</span></a> that is used to add generated <a class="reference internal" href="../glossary#term-special-method"><span class="xref std std-term">special method</span></a>s to classes, as described below.</p> <p>The <a class="reference internal" href="#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass()</code></a> decorator examines the class to find <code>field</code>s. A <code>field</code> is defined as a class variable that has a <a class="reference internal" href="../glossary#term-variable-annotation"><span class="xref std std-term">type annotation</span></a>. With two exceptions described below, nothing in <a class="reference internal" href="#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass()</code></a> examines the type specified in the variable annotation.</p> <p>The order of the fields in all of the generated methods is the order in which they appear in the class definition.</p> <p>The <a class="reference internal" href="#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass()</code></a> decorator will add various “dunder” methods to the class, described below. If any of the added methods already exist in the class, the behavior depends on the parameter, as documented below. The decorator returns the same class that it is called on; no new class is created.</p> <p>If <a class="reference internal" href="#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass()</code></a> is used just as a simple decorator with no parameters, it acts as if it has the default values documented in this signature. That is, these three uses of <a class="reference internal" href="#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass()</code></a> are equivalent:</p> <pre data-language="python">@dataclass +class C: + ... + +@dataclass() +class C: + ... + +@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) +class C: + ... +</pre> <p>The parameters to <a class="reference internal" href="#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass()</code></a> are:</p> <ul> <li> +<p><code>init</code>: If true (the default), a <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> method will be generated.</p> <p>If the class already defines <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a>, this parameter is ignored.</p> </li> <li> +<p><code>repr</code>: If true (the default), a <a class="reference internal" href="../reference/datamodel#object.__repr__" title="object.__repr__"><code>__repr__()</code></a> method will be generated. The generated repr string will have the class name and the name and repr of each field, in the order they are defined in the class. Fields that are marked as being excluded from the repr are not included. For example: <code>InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10)</code>.</p> <p>If the class already defines <a class="reference internal" href="../reference/datamodel#object.__repr__" title="object.__repr__"><code>__repr__()</code></a>, this parameter is ignored.</p> </li> <li> +<p><code>eq</code>: If true (the default), an <a class="reference internal" href="../reference/datamodel#object.__eq__" title="object.__eq__"><code>__eq__()</code></a> method will be generated. This method compares the class as if it were a tuple of its fields, in order. Both instances in the comparison must be of the identical type.</p> <p>If the class already defines <a class="reference internal" href="../reference/datamodel#object.__eq__" title="object.__eq__"><code>__eq__()</code></a>, this parameter is ignored.</p> </li> <li> +<p><code>order</code>: If true (the default is <code>False</code>), <a class="reference internal" href="../reference/datamodel#object.__lt__" title="object.__lt__"><code>__lt__()</code></a>, <a class="reference internal" href="../reference/datamodel#object.__le__" title="object.__le__"><code>__le__()</code></a>, <a class="reference internal" href="../reference/datamodel#object.__gt__" title="object.__gt__"><code>__gt__()</code></a>, and <a class="reference internal" href="../reference/datamodel#object.__ge__" title="object.__ge__"><code>__ge__()</code></a> methods will be generated. These compare the class as if it were a tuple of its fields, in order. Both instances in the comparison must be of the identical type. If <code>order</code> is true and <code>eq</code> is false, a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> is raised.</p> <p>If the class already defines any of <a class="reference internal" href="../reference/datamodel#object.__lt__" title="object.__lt__"><code>__lt__()</code></a>, <a class="reference internal" href="../reference/datamodel#object.__le__" title="object.__le__"><code>__le__()</code></a>, <a class="reference internal" href="../reference/datamodel#object.__gt__" title="object.__gt__"><code>__gt__()</code></a>, or <a class="reference internal" href="../reference/datamodel#object.__ge__" title="object.__ge__"><code>__ge__()</code></a>, then <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> is raised.</p> </li> <li> +<p><code>unsafe_hash</code>: If <code>False</code> (the default), a <a class="reference internal" href="../reference/datamodel#object.__hash__" title="object.__hash__"><code>__hash__()</code></a> method is generated according to how <code>eq</code> and <code>frozen</code> are set.</p> <p><a class="reference internal" href="../reference/datamodel#object.__hash__" title="object.__hash__"><code>__hash__()</code></a> is used by built-in <a class="reference internal" href="functions#hash" title="hash"><code>hash()</code></a>, and when objects are added to hashed collections such as dictionaries and sets. Having a <a class="reference internal" href="../reference/datamodel#object.__hash__" title="object.__hash__"><code>__hash__()</code></a> implies that instances of the class are immutable. Mutability is a complicated property that depends on the programmer’s intent, the existence and behavior of <a class="reference internal" href="../reference/datamodel#object.__eq__" title="object.__eq__"><code>__eq__()</code></a>, and the values of the <code>eq</code> and <code>frozen</code> flags in the <a class="reference internal" href="#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass()</code></a> decorator.</p> <p>By default, <a class="reference internal" href="#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass()</code></a> will not implicitly add a <a class="reference internal" href="../reference/datamodel#object.__hash__" title="object.__hash__"><code>__hash__()</code></a> method unless it is safe to do so. Neither will it add or change an existing explicitly defined <a class="reference internal" href="../reference/datamodel#object.__hash__" title="object.__hash__"><code>__hash__()</code></a> method. Setting the class attribute <code>__hash__ = None</code> has a specific meaning to Python, as described in the <a class="reference internal" href="../reference/datamodel#object.__hash__" title="object.__hash__"><code>__hash__()</code></a> documentation.</p> <p>If <a class="reference internal" href="../reference/datamodel#object.__hash__" title="object.__hash__"><code>__hash__()</code></a> is not explicitly defined, or if it is set to <code>None</code>, then <a class="reference internal" href="#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass()</code></a> <em>may</em> add an implicit <a class="reference internal" href="../reference/datamodel#object.__hash__" title="object.__hash__"><code>__hash__()</code></a> method. Although not recommended, you can force <a class="reference internal" href="#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass()</code></a> to create a <a class="reference internal" href="../reference/datamodel#object.__hash__" title="object.__hash__"><code>__hash__()</code></a> method with <code>unsafe_hash=True</code>. This might be the case if your class is logically immutable but can nonetheless be mutated. This is a specialized use case and should be considered carefully.</p> <p>Here are the rules governing implicit creation of a <a class="reference internal" href="../reference/datamodel#object.__hash__" title="object.__hash__"><code>__hash__()</code></a> method. Note that you cannot both have an explicit <a class="reference internal" href="../reference/datamodel#object.__hash__" title="object.__hash__"><code>__hash__()</code></a> method in your dataclass and set <code>unsafe_hash=True</code>; this will result in a <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a>.</p> <p>If <code>eq</code> and <code>frozen</code> are both true, by default <a class="reference internal" href="#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass()</code></a> will generate a <a class="reference internal" href="../reference/datamodel#object.__hash__" title="object.__hash__"><code>__hash__()</code></a> method for you. If <code>eq</code> is true and <code>frozen</code> is false, <a class="reference internal" href="../reference/datamodel#object.__hash__" title="object.__hash__"><code>__hash__()</code></a> will be set to <code>None</code>, marking it unhashable (which it is, since it is mutable). If <code>eq</code> is false, <a class="reference internal" href="../reference/datamodel#object.__hash__" title="object.__hash__"><code>__hash__()</code></a> will be left untouched meaning the <a class="reference internal" href="../reference/datamodel#object.__hash__" title="object.__hash__"><code>__hash__()</code></a> method of the superclass will be used (if the superclass is <a class="reference internal" href="functions#object" title="object"><code>object</code></a>, this means it will fall back to id-based hashing).</p> </li> <li> +<code>frozen</code>: If true (the default is <code>False</code>), assigning to fields will generate an exception. This emulates read-only frozen instances. If <a class="reference internal" href="../reference/datamodel#object.__setattr__" title="object.__setattr__"><code>__setattr__()</code></a> or <a class="reference internal" href="../reference/datamodel#object.__delattr__" title="object.__delattr__"><code>__delattr__()</code></a> is defined in the class, then <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> is raised. See the discussion below.</li> <li> +<code>match_args</code>: If true (the default is <code>True</code>), the <code>__match_args__</code> tuple will be created from the list of parameters to the generated <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> method (even if <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> is not generated, see above). If false, or if <code>__match_args__</code> is already defined in the class, then <code>__match_args__</code> will not be generated.</li> </ul> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> <ul class="simple"> <li> +<code>kw_only</code>: If true (the default value is <code>False</code>), then all fields will be marked as keyword-only. If a field is marked as keyword-only, then the only effect is that the <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> parameter generated from a keyword-only field must be specified with a keyword when <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> is called. There is no effect on any other aspect of dataclasses. See the <a class="reference internal" href="../glossary#term-parameter"><span class="xref std std-term">parameter</span></a> glossary entry for details. Also see the <a class="reference internal" href="#dataclasses.KW_ONLY" title="dataclasses.KW_ONLY"><code>KW_ONLY</code></a> section.</li> </ul> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> <ul class="simple"> <li> +<code>slots</code>: If true (the default is <code>False</code>), <a class="reference internal" href="../reference/datamodel#object.__slots__" title="object.__slots__"><code>__slots__</code></a> attribute will be generated and new class will be returned instead of the original one. If <a class="reference internal" href="../reference/datamodel#object.__slots__" title="object.__slots__"><code>__slots__</code></a> is already defined in the class, then <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> is raised.</li> </ul> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>If a field name is already included in the <code>__slots__</code> of a base class, it will not be included in the generated <code>__slots__</code> to prevent <a class="reference internal" href="../reference/datamodel#datamodel-note-slots"><span class="std std-ref">overriding them</span></a>. Therefore, do not use <code>__slots__</code> to retrieve the field names of a dataclass. Use <a class="reference internal" href="#dataclasses.fields" title="dataclasses.fields"><code>fields()</code></a> instead. To be able to determine inherited slots, base class <code>__slots__</code> may be any iterable, but <em>not</em> an iterator.</p> </div> <ul class="simple"> <li> +<code>weakref_slot</code>: If true (the default is <code>False</code>), add a slot named “__weakref__”, which is required to make an instance weakref-able. It is an error to specify <code>weakref_slot=True</code> without also specifying <code>slots=True</code>.</li> </ul> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.11.</span></p> </div> <p><code>field</code>s may optionally specify a default value, using normal Python syntax:</p> <pre data-language="python">@dataclass +class C: + a: int # 'a' has no default value + b: int = 0 # assign a default value for 'b' +</pre> <p>In this example, both <code>a</code> and <code>b</code> will be included in the added <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> method, which will be defined as:</p> <pre data-language="python">def __init__(self, a: int, b: int = 0): +</pre> <p><a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> will be raised if a field without a default value follows a field with a default value. This is true whether this occurs in a single class, or as a result of class inheritance.</p> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="dataclasses.field"> +<code>dataclasses.field(*, default=MISSING, default_factory=MISSING, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=MISSING)</code> </dt> <dd> +<p>For common and simple use cases, no other functionality is required. There are, however, some dataclass features that require additional per-field information. To satisfy this need for additional information, you can replace the default field value with a call to the provided <a class="reference internal" href="#dataclasses.field" title="dataclasses.field"><code>field()</code></a> function. For example:</p> <pre data-language="python">@dataclass +class C: + mylist: list[int] = field(default_factory=list) + +c = C() +c.mylist += [1, 2, 3] +</pre> <p>As shown above, the <a class="reference internal" href="#dataclasses.MISSING" title="dataclasses.MISSING"><code>MISSING</code></a> value is a sentinel object used to detect if some parameters are provided by the user. This sentinel is used because <code>None</code> is a valid value for some parameters with a distinct meaning. No code should directly use the <a class="reference internal" href="#dataclasses.MISSING" title="dataclasses.MISSING"><code>MISSING</code></a> value.</p> <p>The parameters to <a class="reference internal" href="#dataclasses.field" title="dataclasses.field"><code>field()</code></a> are:</p> <ul> <li> +<code>default</code>: If provided, this will be the default value for this field. This is needed because the <a class="reference internal" href="#dataclasses.field" title="dataclasses.field"><code>field()</code></a> call itself replaces the normal position of the default value.</li> <li> +<code>default_factory</code>: If provided, it must be a zero-argument callable that will be called when a default value is needed for this field. Among other purposes, this can be used to specify fields with mutable default values, as discussed below. It is an error to specify both <code>default</code> and <code>default_factory</code>.</li> <li> +<code>init</code>: If true (the default), this field is included as a parameter to the generated <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> method.</li> <li> +<code>repr</code>: If true (the default), this field is included in the string returned by the generated <a class="reference internal" href="../reference/datamodel#object.__repr__" title="object.__repr__"><code>__repr__()</code></a> method.</li> <li> +<p><code>hash</code>: This can be a bool or <code>None</code>. If true, this field is included in the generated <a class="reference internal" href="../reference/datamodel#object.__hash__" title="object.__hash__"><code>__hash__()</code></a> method. If <code>None</code> (the default), use the value of <code>compare</code>: this would normally be the expected behavior. A field should be considered in the hash if it’s used for comparisons. Setting this value to anything other than <code>None</code> is discouraged.</p> <p>One possible reason to set <code>hash=False</code> but <code>compare=True</code> would be if a field is expensive to compute a hash value for, that field is needed for equality testing, and there are other fields that contribute to the type’s hash value. Even if a field is excluded from the hash, it will still be used for comparisons.</p> </li> <li> +<code>compare</code>: If true (the default), this field is included in the generated equality and comparison methods (<a class="reference internal" href="../reference/datamodel#object.__eq__" title="object.__eq__"><code>__eq__()</code></a>, <a class="reference internal" href="../reference/datamodel#object.__gt__" title="object.__gt__"><code>__gt__()</code></a>, et al.).</li> <li> +<code>metadata</code>: This can be a mapping or None. None is treated as an empty dict. This value is wrapped in <a class="reference internal" href="types#types.MappingProxyType" title="types.MappingProxyType"><code>MappingProxyType()</code></a> to make it read-only, and exposed on the <a class="reference internal" href="#dataclasses.Field" title="dataclasses.Field"><code>Field</code></a> object. It is not used at all by Data Classes, and is provided as a third-party extension mechanism. Multiple third-parties can each have their own key, to use as a namespace in the metadata.</li> <li> +<code>kw_only</code>: If true, this field will be marked as keyword-only. This is used when the generated <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> method’s parameters are computed.</li> </ul> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> <p>If the default value of a field is specified by a call to <a class="reference internal" href="#dataclasses.field" title="dataclasses.field"><code>field()</code></a>, then the class attribute for this field will be replaced by the specified <code>default</code> value. If no <code>default</code> is provided, then the class attribute will be deleted. The intent is that after the <a class="reference internal" href="#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass()</code></a> decorator runs, the class attributes will all contain the default values for the fields, just as if the default value itself were specified. For example, after:</p> <pre data-language="python">@dataclass +class C: + x: int + y: int = field(repr=False) + z: int = field(repr=False, default=10) + t: int = 20 +</pre> <p>The class attribute <code>C.z</code> will be <code>10</code>, the class attribute <code>C.t</code> will be <code>20</code>, and the class attributes <code>C.x</code> and <code>C.y</code> will not be set.</p> </dd> +</dl> <dl class="py class"> <dt class="sig sig-object py" id="dataclasses.Field"> +<code>class dataclasses.Field</code> </dt> <dd> +<p><a class="reference internal" href="#dataclasses.Field" title="dataclasses.Field"><code>Field</code></a> objects describe each defined field. These objects are created internally, and are returned by the <a class="reference internal" href="#dataclasses.fields" title="dataclasses.fields"><code>fields()</code></a> module-level method (see below). Users should never instantiate a <a class="reference internal" href="#dataclasses.Field" title="dataclasses.Field"><code>Field</code></a> object directly. Its documented attributes are:</p> <ul class="simple"> <li> +<code>name</code>: The name of the field.</li> <li> +<code>type</code>: The type of the field.</li> <li> +<code>default</code>, <code>default_factory</code>, <code>init</code>, <code>repr</code>, <code>hash</code>, <code>compare</code>, <code>metadata</code>, and <code>kw_only</code> have the identical meaning and values as they do in the <a class="reference internal" href="#dataclasses.field" title="dataclasses.field"><code>field()</code></a> function.</li> </ul> <p>Other attributes may exist, but they are private and must not be inspected or relied on.</p> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="dataclasses.fields"> +<code>dataclasses.fields(class_or_instance)</code> </dt> <dd> +<p>Returns a tuple of <a class="reference internal" href="#dataclasses.Field" title="dataclasses.Field"><code>Field</code></a> objects that define the fields for this dataclass. Accepts either a dataclass, or an instance of a dataclass. Raises <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> if not passed a dataclass or instance of one. Does not return pseudo-fields which are <code>ClassVar</code> or <code>InitVar</code>.</p> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="dataclasses.asdict"> +<code>dataclasses.asdict(obj, *, dict_factory=dict)</code> </dt> <dd> +<p>Converts the dataclass <code>obj</code> to a dict (by using the factory function <code>dict_factory</code>). Each dataclass is converted to a dict of its fields, as <code>name: value</code> pairs. dataclasses, dicts, lists, and tuples are recursed into. Other objects are copied with <a class="reference internal" href="copy#copy.deepcopy" title="copy.deepcopy"><code>copy.deepcopy()</code></a>.</p> <p>Example of using <a class="reference internal" href="#dataclasses.asdict" title="dataclasses.asdict"><code>asdict()</code></a> on nested dataclasses:</p> <pre data-language="python">@dataclass +class Point: + x: int + y: int + +@dataclass +class C: + mylist: list[Point] + +p = Point(10, 20) +assert asdict(p) == {'x': 10, 'y': 20} + +c = C([Point(0, 0), Point(10, 4)]) +assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]} +</pre> <p>To create a shallow copy, the following workaround may be used:</p> <pre data-language="python">dict((field.name, getattr(obj, field.name)) for field in fields(obj)) +</pre> <p><a class="reference internal" href="#dataclasses.asdict" title="dataclasses.asdict"><code>asdict()</code></a> raises <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> if <code>obj</code> is not a dataclass instance.</p> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="dataclasses.astuple"> +<code>dataclasses.astuple(obj, *, tuple_factory=tuple)</code> </dt> <dd> +<p>Converts the dataclass <code>obj</code> to a tuple (by using the factory function <code>tuple_factory</code>). Each dataclass is converted to a tuple of its field values. dataclasses, dicts, lists, and tuples are recursed into. Other objects are copied with <a class="reference internal" href="copy#copy.deepcopy" title="copy.deepcopy"><code>copy.deepcopy()</code></a>.</p> <p>Continuing from the previous example:</p> <pre data-language="python">assert astuple(p) == (10, 20) +assert astuple(c) == ([(0, 0), (10, 4)],) +</pre> <p>To create a shallow copy, the following workaround may be used:</p> <pre data-language="python">tuple(getattr(obj, field.name) for field in dataclasses.fields(obj)) +</pre> <p><a class="reference internal" href="#dataclasses.astuple" title="dataclasses.astuple"><code>astuple()</code></a> raises <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a> if <code>obj</code> is not a dataclass instance.</p> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="dataclasses.make_dataclass"> +<code>dataclasses.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)</code> </dt> <dd> +<p>Creates a new dataclass with name <code>cls_name</code>, fields as defined in <code>fields</code>, base classes as given in <code>bases</code>, and initialized with a namespace as given in <code>namespace</code>. <code>fields</code> is an iterable whose elements are each either <code>name</code>, <code>(name, type)</code>, or <code>(name, type, Field)</code>. If just <code>name</code> is supplied, <code>typing.Any</code> is used for <code>type</code>. The values of <code>init</code>, <code>repr</code>, <code>eq</code>, <code>order</code>, <code>unsafe_hash</code>, <code>frozen</code>, <code>match_args</code>, <code>kw_only</code>, <code>slots</code>, and <code>weakref_slot</code> have the same meaning as they do in <a class="reference internal" href="#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass()</code></a>.</p> <p>If <code>module</code> is defined, the <code>__module__</code> attribute of the dataclass is set to that value. By default, it is set to the module name of the caller.</p> <p>This function is not strictly required, because any Python mechanism for creating a new class with <code>__annotations__</code> can then apply the <a class="reference internal" href="#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass()</code></a> function to convert that class to a dataclass. This function is provided as a convenience. For example:</p> <pre data-language="python">C = make_dataclass('C', + [('x', int), + 'y', + ('z', int, field(default=5))], + namespace={'add_one': lambda self: self.x + 1}) +</pre> <p>Is equivalent to:</p> <pre data-language="python">@dataclass +class C: + x: int + y: 'typing.Any' + z: int = 5 + + def add_one(self): + return self.x + 1 +</pre> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="dataclasses.replace"> +<code>dataclasses.replace(obj, /, **changes)</code> </dt> <dd> +<p>Creates a new object of the same type as <code>obj</code>, replacing fields with values from <code>changes</code>. If <code>obj</code> is not a Data Class, raises <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a>. If values in <code>changes</code> do not specify fields, raises <a class="reference internal" href="exceptions#TypeError" title="TypeError"><code>TypeError</code></a>.</p> <p>The newly returned object is created by calling the <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> method of the dataclass. This ensures that <a class="reference internal" href="#dataclasses.__post_init__" title="dataclasses.__post_init__"><code>__post_init__()</code></a>, if present, is also called.</p> <p>Init-only variables without default values, if any exist, must be specified on the call to <a class="reference internal" href="#dataclasses.replace" title="dataclasses.replace"><code>replace()</code></a> so that they can be passed to <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> and <a class="reference internal" href="#dataclasses.__post_init__" title="dataclasses.__post_init__"><code>__post_init__()</code></a>.</p> <p>It is an error for <code>changes</code> to contain any fields that are defined as having <code>init=False</code>. A <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> will be raised in this case.</p> <p>Be forewarned about how <code>init=False</code> fields work during a call to <a class="reference internal" href="#dataclasses.replace" title="dataclasses.replace"><code>replace()</code></a>. They are not copied from the source object, but rather are initialized in <a class="reference internal" href="#dataclasses.__post_init__" title="dataclasses.__post_init__"><code>__post_init__()</code></a>, if they’re initialized at all. It is expected that <code>init=False</code> fields will be rarely and judiciously used. If they are used, it might be wise to have alternate class constructors, or perhaps a custom <code>replace()</code> (or similarly named) method which handles instance copying.</p> </dd> +</dl> <dl class="py function"> <dt class="sig sig-object py" id="dataclasses.is_dataclass"> +<code>dataclasses.is_dataclass(obj)</code> </dt> <dd> +<p>Return <code>True</code> if its parameter is a dataclass or an instance of one, otherwise return <code>False</code>.</p> <p>If you need to know if a class is an instance of a dataclass (and not a dataclass itself), then add a further check for <code>not +isinstance(obj, type)</code>:</p> <pre data-language="python">def is_dataclass_instance(obj): + return is_dataclass(obj) and not isinstance(obj, type) +</pre> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="dataclasses.MISSING"> +<code>dataclasses.MISSING</code> </dt> <dd> +<p>A sentinel value signifying a missing default or default_factory.</p> </dd> +</dl> <dl class="py data"> <dt class="sig sig-object py" id="dataclasses.KW_ONLY"> +<code>dataclasses.KW_ONLY</code> </dt> <dd> +<p>A sentinel value used as a type annotation. Any fields after a pseudo-field with the type of <a class="reference internal" href="#dataclasses.KW_ONLY" title="dataclasses.KW_ONLY"><code>KW_ONLY</code></a> are marked as keyword-only fields. Note that a pseudo-field of type <a class="reference internal" href="#dataclasses.KW_ONLY" title="dataclasses.KW_ONLY"><code>KW_ONLY</code></a> is otherwise completely ignored. This includes the name of such a field. By convention, a name of <code>_</code> is used for a <a class="reference internal" href="#dataclasses.KW_ONLY" title="dataclasses.KW_ONLY"><code>KW_ONLY</code></a> field. Keyword-only fields signify <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> parameters that must be specified as keywords when the class is instantiated.</p> <p>In this example, the fields <code>y</code> and <code>z</code> will be marked as keyword-only fields:</p> <pre data-language="python">@dataclass +class Point: + x: float + _: KW_ONLY + y: float + z: float + +p = Point(0, y=1.5, z=2.0) +</pre> <p>In a single dataclass, it is an error to specify more than one field whose type is <a class="reference internal" href="#dataclasses.KW_ONLY" title="dataclasses.KW_ONLY"><code>KW_ONLY</code></a>.</p> <div class="versionadded"> <p><span class="versionmodified added">New in version 3.10.</span></p> </div> </dd> +</dl> <dl class="py exception"> <dt class="sig sig-object py" id="dataclasses.FrozenInstanceError"> +<code>exception dataclasses.FrozenInstanceError</code> </dt> <dd> +<p>Raised when an implicitly defined <a class="reference internal" href="../reference/datamodel#object.__setattr__" title="object.__setattr__"><code>__setattr__()</code></a> or <a class="reference internal" href="../reference/datamodel#object.__delattr__" title="object.__delattr__"><code>__delattr__()</code></a> is called on a dataclass which was defined with <code>frozen=True</code>. It is a subclass of <a class="reference internal" href="exceptions#AttributeError" title="AttributeError"><code>AttributeError</code></a>.</p> </dd> +</dl> </section> <section id="post-init-processing"> <span id="id1"></span><h2>Post-init processing</h2> <dl class="py function"> <dt class="sig sig-object py" id="dataclasses.__post_init__"> +<code>dataclasses.__post_init__()</code> </dt> <dd> +<p>When defined on the class, it will be called by the generated <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a>, normally as <code>self.__post_init__()</code>. However, if any <code>InitVar</code> fields are defined, they will also be passed to <a class="reference internal" href="#dataclasses.__post_init__" title="dataclasses.__post_init__"><code>__post_init__()</code></a> in the order they were defined in the class. If no <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> method is generated, then <a class="reference internal" href="#dataclasses.__post_init__" title="dataclasses.__post_init__"><code>__post_init__()</code></a> will not automatically be called.</p> <p>Among other uses, this allows for initializing field values that depend on one or more other fields. For example:</p> <pre data-language="python">@dataclass +class C: + a: float + b: float + c: float = field(init=False) + + def __post_init__(self): + self.c = self.a + self.b +</pre> </dd> +</dl> <p>The <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> method generated by <a class="reference internal" href="#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass()</code></a> does not call base class <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> methods. If the base class has an <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> method that has to be called, it is common to call this method in a <a class="reference internal" href="#dataclasses.__post_init__" title="dataclasses.__post_init__"><code>__post_init__()</code></a> method:</p> <pre data-language="python">@dataclass +class Rectangle: + height: float + width: float + +@dataclass +class Square(Rectangle): + side: float + + def __post_init__(self): + super().__init__(self.side, self.side) +</pre> <p>Note, however, that in general the dataclass-generated <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> methods don’t need to be called, since the derived dataclass will take care of initializing all fields of any base class that is a dataclass itself.</p> <p>See the section below on init-only variables for ways to pass parameters to <a class="reference internal" href="#dataclasses.__post_init__" title="dataclasses.__post_init__"><code>__post_init__()</code></a>. Also see the warning about how <a class="reference internal" href="#dataclasses.replace" title="dataclasses.replace"><code>replace()</code></a> handles <code>init=False</code> fields.</p> </section> <section id="class-variables"> <h2>Class variables</h2> <p>One of the few places where <a class="reference internal" href="#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass()</code></a> actually inspects the type of a field is to determine if a field is a class variable as defined in <span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-0526/"><strong>PEP 526</strong></a>. It does this by checking if the type of the field is <code>typing.ClassVar</code>. If a field is a <code>ClassVar</code>, it is excluded from consideration as a field and is ignored by the dataclass mechanisms. Such <code>ClassVar</code> pseudo-fields are not returned by the module-level <a class="reference internal" href="#dataclasses.fields" title="dataclasses.fields"><code>fields()</code></a> function.</p> </section> <section id="init-only-variables"> <h2>Init-only variables</h2> <p>Another place where <a class="reference internal" href="#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass()</code></a> inspects a type annotation is to determine if a field is an init-only variable. It does this by seeing if the type of a field is of type <code>dataclasses.InitVar</code>. If a field is an <code>InitVar</code>, it is considered a pseudo-field called an init-only field. As it is not a true field, it is not returned by the module-level <a class="reference internal" href="#dataclasses.fields" title="dataclasses.fields"><code>fields()</code></a> function. Init-only fields are added as parameters to the generated <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> method, and are passed to the optional <a class="reference internal" href="#dataclasses.__post_init__" title="dataclasses.__post_init__"><code>__post_init__()</code></a> method. They are not otherwise used by dataclasses.</p> <p>For example, suppose a field will be initialized from a database, if a value is not provided when creating the class:</p> <pre data-language="python">@dataclass +class C: + i: int + j: int | None = None + database: InitVar[DatabaseType | None] = None + + def __post_init__(self, database): + if self.j is None and database is not None: + self.j = database.lookup('j') + +c = C(10, database=my_database) +</pre> <p>In this case, <a class="reference internal" href="#dataclasses.fields" title="dataclasses.fields"><code>fields()</code></a> will return <a class="reference internal" href="#dataclasses.Field" title="dataclasses.Field"><code>Field</code></a> objects for <code>i</code> and <code>j</code>, but not for <code>database</code>.</p> </section> <section id="frozen-instances"> <h2>Frozen instances</h2> <p>It is not possible to create truly immutable Python objects. However, by passing <code>frozen=True</code> to the <a class="reference internal" href="#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass()</code></a> decorator you can emulate immutability. In that case, dataclasses will add <a class="reference internal" href="../reference/datamodel#object.__setattr__" title="object.__setattr__"><code>__setattr__()</code></a> and <a class="reference internal" href="../reference/datamodel#object.__delattr__" title="object.__delattr__"><code>__delattr__()</code></a> methods to the class. These methods will raise a <a class="reference internal" href="#dataclasses.FrozenInstanceError" title="dataclasses.FrozenInstanceError"><code>FrozenInstanceError</code></a> when invoked.</p> <p>There is a tiny performance penalty when using <code>frozen=True</code>: <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> cannot use simple assignment to initialize fields, and must use <code>object.__setattr__()</code>.</p> </section> <section id="inheritance"> <h2>Inheritance</h2> <p>When the dataclass is being created by the <a class="reference internal" href="#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass()</code></a> decorator, it looks through all of the class’s base classes in reverse MRO (that is, starting at <a class="reference internal" href="functions#object" title="object"><code>object</code></a>) and, for each dataclass that it finds, adds the fields from that base class to an ordered mapping of fields. After all of the base class fields are added, it adds its own fields to the ordered mapping. All of the generated methods will use this combined, calculated ordered mapping of fields. Because the fields are in insertion order, derived classes override base classes. An example:</p> <pre data-language="python">@dataclass +class Base: + x: Any = 15.0 + y: int = 0 + +@dataclass +class C(Base): + z: int = 10 + x: int = 15 +</pre> <p>The final list of fields is, in order, <code>x</code>, <code>y</code>, <code>z</code>. The final type of <code>x</code> is <code>int</code>, as specified in class <code>C</code>.</p> <p>The generated <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> method for <code>C</code> will look like:</p> <pre data-language="python">def __init__(self, x: int = 15, y: int = 0, z: int = 10): +</pre> </section> <section id="re-ordering-of-keyword-only-parameters-in-init"> <h2>Re-ordering of keyword-only parameters in __init__()</h2> <p>After the parameters needed for <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> are computed, any keyword-only parameters are moved to come after all regular (non-keyword-only) parameters. This is a requirement of how keyword-only parameters are implemented in Python: they must come after non-keyword-only parameters.</p> <p>In this example, <code>Base.y</code>, <code>Base.w</code>, and <code>D.t</code> are keyword-only fields, and <code>Base.x</code> and <code>D.z</code> are regular fields:</p> <pre data-language="python">@dataclass +class Base: + x: Any = 15.0 + _: KW_ONLY + y: int = 0 + w: int = 1 + +@dataclass +class D(Base): + z: int = 10 + t: int = field(kw_only=True, default=0) +</pre> <p>The generated <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> method for <code>D</code> will look like:</p> <pre data-language="python">def __init__(self, x: Any = 15.0, z: int = 10, *, y: int = 0, w: int = 1, t: int = 0): +</pre> <p>Note that the parameters have been re-ordered from how they appear in the list of fields: parameters derived from regular fields are followed by parameters derived from keyword-only fields.</p> <p>The relative ordering of keyword-only parameters is maintained in the re-ordered <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> parameter list.</p> </section> <section id="default-factory-functions"> <h2>Default factory functions</h2> <p>If a <a class="reference internal" href="#dataclasses.field" title="dataclasses.field"><code>field()</code></a> specifies a <code>default_factory</code>, it is called with zero arguments when a default value for the field is needed. For example, to create a new instance of a list, use:</p> <pre data-language="python">mylist: list = field(default_factory=list) +</pre> <p>If a field is excluded from <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> (using <code>init=False</code>) and the field also specifies <code>default_factory</code>, then the default factory function will always be called from the generated <a class="reference internal" href="../reference/datamodel#object.__init__" title="object.__init__"><code>__init__()</code></a> function. This happens because there is no other way to give the field an initial value.</p> </section> <section id="mutable-default-values"> <h2>Mutable default values</h2> <p>Python stores default member variable values in class attributes. Consider this example, not using dataclasses:</p> <pre data-language="python">class C: + x = [] + def add(self, element): + self.x.append(element) + +o1 = C() +o2 = C() +o1.add(1) +o2.add(2) +assert o1.x == [1, 2] +assert o1.x is o2.x +</pre> <p>Note that the two instances of class <code>C</code> share the same class variable <code>x</code>, as expected.</p> <p>Using dataclasses, <em>if</em> this code was valid:</p> <pre data-language="python">@dataclass +class D: + x: list = [] # This code raises ValueError + def add(self, element): + self.x += element +</pre> <p>it would generate code similar to:</p> <pre data-language="python">class D: + x = [] + def __init__(self, x=x): + self.x = x + def add(self, element): + self.x += element + +assert D().x is D().x +</pre> <p>This has the same issue as the original example using class <code>C</code>. That is, two instances of class <code>D</code> that do not specify a value for <code>x</code> when creating a class instance will share the same copy of <code>x</code>. Because dataclasses just use normal Python class creation they also share this behavior. There is no general way for Data Classes to detect this condition. Instead, the <a class="reference internal" href="#dataclasses.dataclass" title="dataclasses.dataclass"><code>dataclass()</code></a> decorator will raise a <a class="reference internal" href="exceptions#ValueError" title="ValueError"><code>ValueError</code></a> if it detects an unhashable default parameter. The assumption is that if a value is unhashable, it is mutable. This is a partial solution, but it does protect against many common errors.</p> <p>Using default factory functions is a way to create new instances of mutable types as default values for fields:</p> <pre data-language="python">@dataclass +class D: + x: list = field(default_factory=list) + +assert D().x is not D().x +</pre> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.11: </span>Instead of looking for and disallowing objects of type <code>list</code>, <code>dict</code>, or <code>set</code>, unhashable objects are now not allowed as default values. Unhashability is used to approximate mutability.</p> </div> </section> <section id="descriptor-typed-fields"> <h2>Descriptor-typed fields</h2> <p>Fields that are assigned <a class="reference internal" href="../reference/datamodel#descriptors"><span class="std std-ref">descriptor objects</span></a> as their default value have the following special behaviors:</p> <ul class="simple"> <li>The value for the field passed to the dataclass’s <code>__init__</code> method is passed to the descriptor’s <code>__set__</code> method rather than overwriting the descriptor object.</li> <li>Similarly, when getting or setting the field, the descriptor’s <code>__get__</code> or <code>__set__</code> method is called rather than returning or overwriting the descriptor object.</li> <li>To determine whether a field contains a default value, <code>dataclasses</code> will call the descriptor’s <code>__get__</code> method using its class access form (i.e. <code>descriptor.__get__(obj=None, type=cls)</code>. If the descriptor returns a value in this case, it will be used as the field’s default. On the other hand, if the descriptor raises <a class="reference internal" href="exceptions#AttributeError" title="AttributeError"><code>AttributeError</code></a> in this situation, no default value will be provided for the field.</li> </ul> <pre data-language="python">class IntConversionDescriptor: + def __init__(self, *, default): + self._default = default + + def __set_name__(self, owner, name): + self._name = "_" + name + + def __get__(self, obj, type): + if obj is None: + return self._default + + return getattr(obj, self._name, self._default) + + def __set__(self, obj, value): + setattr(obj, self._name, int(value)) + +@dataclass +class InventoryItem: + quantity_on_hand: IntConversionDescriptor = IntConversionDescriptor(default=100) + +i = InventoryItem() +print(i.quantity_on_hand) # 100 +i.quantity_on_hand = 2.5 # calls __set__ with 2.5 +print(i.quantity_on_hand) # 2 +</pre> <p>Note that if a field is annotated with a descriptor type, but is not assigned a descriptor object as its default value, the field will act like a normal field.</p> </section> <div class="_attribution"> + <p class="_attribution-p"> + © 2001–2023 Python Software Foundation<br>Licensed under the PSF License.<br> + <a href="https://docs.python.org/3.12/library/dataclasses.html" class="_attribution-link">https://docs.python.org/3.12/library/dataclasses.html</a> + </p> +</div> |
