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