2024-03-21 16:47:09 -03:00
|
|
|
:mod:`!dataclasses` --- Data Classes
|
|
|
|
====================================
|
2018-05-16 05:20:43 -03:00
|
|
|
|
|
|
|
.. module:: dataclasses
|
2018-05-16 10:29:05 -03:00
|
|
|
:synopsis: Generate special methods on user-defined classes.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
|
|
|
.. moduleauthor:: Eric V. Smith <eric@trueblade.com>
|
|
|
|
.. sectionauthor:: Eric V. Smith <eric@trueblade.com>
|
|
|
|
|
|
|
|
**Source code:** :source:`Lib/dataclasses.py`
|
|
|
|
|
|
|
|
--------------
|
|
|
|
|
|
|
|
This module provides a decorator and functions for automatically
|
2024-04-14 13:29:01 -03:00
|
|
|
adding generated :term:`special methods <special method>` such as :meth:`~object.__init__` and
|
2023-04-24 20:26:18 -03:00
|
|
|
:meth:`~object.__repr__` to user-defined classes. It was originally described
|
2018-05-16 05:20:43 -03:00
|
|
|
in :pep:`557`.
|
|
|
|
|
|
|
|
The member variables to use in these generated methods are defined
|
2021-05-06 18:52:46 -03:00
|
|
|
using :pep:`526` type annotations. For example, this code::
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2020-05-08 08:39:57 -03:00
|
|
|
from dataclasses import dataclass
|
|
|
|
|
2018-05-16 05:20:43 -03:00
|
|
|
@dataclass
|
|
|
|
class InventoryItem:
|
2020-07-09 09:13:47 -03:00
|
|
|
"""Class for keeping track of an item in inventory."""
|
2018-05-16 05:20:43 -03:00
|
|
|
name: str
|
|
|
|
unit_price: float
|
|
|
|
quantity_on_hand: int = 0
|
|
|
|
|
|
|
|
def total_cost(self) -> float:
|
|
|
|
return self.unit_price * self.quantity_on_hand
|
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
will add, among other things, a :meth:`!__init__` that looks like::
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2021-04-30 20:06:55 -03:00
|
|
|
def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0):
|
2018-05-16 05:20:43 -03:00
|
|
|
self.name = name
|
|
|
|
self.unit_price = unit_price
|
|
|
|
self.quantity_on_hand = quantity_on_hand
|
|
|
|
|
|
|
|
Note that this method is automatically added to the class: it is not
|
2024-04-14 13:29:01 -03:00
|
|
|
directly specified in the :class:`!InventoryItem` definition shown above.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
|
|
|
.. versionadded:: 3.7
|
|
|
|
|
2021-05-02 22:20:50 -03:00
|
|
|
Module contents
|
|
|
|
---------------
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2022-05-02 13:36:39 -03:00
|
|
|
.. 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)
|
2018-05-16 05:20:43 -03:00
|
|
|
|
|
|
|
This function is a :term:`decorator` that is used to add generated
|
2024-03-21 16:47:09 -03:00
|
|
|
:term:`special methods <special method>` to classes, as described below.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
The ``@dataclass`` decorator examines the class to find
|
2021-05-06 18:52:46 -03:00
|
|
|
``field``\s. A ``field`` is defined as a class variable that has a
|
2018-12-24 01:09:09 -04:00
|
|
|
:term:`type annotation <variable annotation>`. With two
|
2024-03-21 16:47:09 -03:00
|
|
|
exceptions described below, nothing in ``@dataclass``
|
2018-12-24 01:09:09 -04:00
|
|
|
examines the type specified in the variable annotation.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
|
|
|
The order of the fields in all of the generated methods is the
|
|
|
|
order in which they appear in the class definition.
|
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
The ``@dataclass`` decorator will add various "dunder" methods to
|
2018-05-16 05:20:43 -03:00
|
|
|
the class, described below. If any of the added methods already
|
2021-05-06 18:52:46 -03:00
|
|
|
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
|
2019-12-25 18:45:30 -04:00
|
|
|
class is created.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
If ``@dataclass`` is used just as a simple decorator with no parameters,
|
2018-05-16 05:20:43 -03:00
|
|
|
it acts as if it has the default values documented in this
|
2024-03-21 16:47:09 -03:00
|
|
|
signature. That is, these three uses of ``@dataclass`` are
|
2018-05-16 05:20:43 -03:00
|
|
|
equivalent::
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class C:
|
|
|
|
...
|
|
|
|
|
|
|
|
@dataclass()
|
|
|
|
class C:
|
|
|
|
...
|
|
|
|
|
2022-12-05 14:56:13 -04:00
|
|
|
@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)
|
2018-05-16 05:20:43 -03:00
|
|
|
class C:
|
2022-10-29 14:06:52 -03:00
|
|
|
...
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
The parameters to ``@dataclass`` are:
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
- *init*: If true (the default), a :meth:`~object.__init__` method will be
|
2018-05-16 05:20:43 -03:00
|
|
|
generated.
|
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
If the class already defines :meth:`!__init__`, this parameter is
|
2018-05-16 05:20:43 -03:00
|
|
|
ignored.
|
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
- *repr*: If true (the default), a :meth:`~object.__repr__` method will be
|
2018-05-16 05:20:43 -03:00
|
|
|
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:
|
|
|
|
``InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10)``.
|
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
If the class already defines :meth:`!__repr__`, this parameter is
|
2018-05-16 05:20:43 -03:00
|
|
|
ignored.
|
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
- *eq*: If true (the default), an :meth:`~object.__eq__` method will be
|
2018-05-16 05:20:43 -03:00
|
|
|
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.
|
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
If the class already defines :meth:`!__eq__`, this parameter is
|
2018-05-16 05:20:43 -03:00
|
|
|
ignored.
|
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
- *order*: If true (the default is ``False``), :meth:`~object.__lt__`,
|
2023-04-24 20:26:18 -03:00
|
|
|
:meth:`~object.__le__`, :meth:`~object.__gt__`, and :meth:`~object.__ge__` methods will be
|
2018-05-16 05:20:43 -03:00
|
|
|
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
|
2024-04-14 13:29:01 -03:00
|
|
|
identical type. If *order* is true and *eq* is false, a
|
2018-05-16 05:20:43 -03:00
|
|
|
:exc:`ValueError` is raised.
|
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
If the class already defines any of :meth:`!__lt__`,
|
|
|
|
:meth:`!__le__`, :meth:`!__gt__`, or :meth:`!__ge__`, then
|
2019-12-25 18:45:30 -04:00
|
|
|
:exc:`TypeError` is raised.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
- *unsafe_hash*: If ``False`` (the default), a :meth:`~object.__hash__` method
|
|
|
|
is generated according to how *eq* and *frozen* are set.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
:meth:`!__hash__` is used by built-in :meth:`hash()`, and when objects are
|
2018-05-16 16:50:07 -03:00
|
|
|
added to hashed collections such as dictionaries and sets. Having a
|
2024-03-21 16:47:09 -03:00
|
|
|
:meth:`!__hash__` implies that instances of the class are immutable.
|
2018-05-16 16:50:07 -03:00
|
|
|
Mutability is a complicated property that depends on the programmer's
|
2024-03-21 16:47:09 -03:00
|
|
|
intent, the existence and behavior of :meth:`!__eq__`, and the values of
|
2024-04-14 13:29:01 -03:00
|
|
|
the *eq* and *frozen* flags in the ``@dataclass`` decorator.
|
2018-05-16 16:50:07 -03:00
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
By default, ``@dataclass`` will not implicitly add a :meth:`~object.__hash__`
|
2018-05-16 16:50:07 -03:00
|
|
|
method unless it is safe to do so. Neither will it add or change an
|
2024-03-21 16:47:09 -03:00
|
|
|
existing explicitly defined :meth:`!__hash__` method. Setting the class
|
2018-05-16 16:50:07 -03:00
|
|
|
attribute ``__hash__ = None`` has a specific meaning to Python, as
|
2024-03-21 16:47:09 -03:00
|
|
|
described in the :meth:`!__hash__` documentation.
|
2018-05-16 16:50:07 -03:00
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
If :meth:`!__hash__` is not explicitly defined, or if it is set to ``None``,
|
|
|
|
then ``@dataclass`` *may* add an implicit :meth:`!__hash__` method.
|
|
|
|
Although not recommended, you can force ``@dataclass`` to create a
|
|
|
|
:meth:`!__hash__` method with ``unsafe_hash=True``. This might be the case
|
2024-01-26 09:42:49 -04:00
|
|
|
if your class is logically immutable but can still be mutated.
|
2018-05-16 16:50:07 -03:00
|
|
|
This is a specialized use case and should be considered carefully.
|
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
Here are the rules governing implicit creation of a :meth:`!__hash__`
|
|
|
|
method. Note that you cannot both have an explicit :meth:`!__hash__`
|
2018-05-16 16:50:07 -03:00
|
|
|
method in your dataclass and set ``unsafe_hash=True``; this will result
|
|
|
|
in a :exc:`TypeError`.
|
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
If *eq* and *frozen* are both true, by default ``@dataclass`` will
|
|
|
|
generate a :meth:`!__hash__` method for you. If *eq* is true and
|
|
|
|
*frozen* is false, :meth:`!__hash__` will be set to ``None``, marking it
|
|
|
|
unhashable (which it is, since it is mutable). If *eq* is false,
|
2024-03-21 16:47:09 -03:00
|
|
|
:meth:`!__hash__` will be left untouched meaning the :meth:`!__hash__`
|
2018-05-16 16:50:07 -03:00
|
|
|
method of the superclass will be used (if the superclass is
|
|
|
|
:class:`object`, this means it will fall back to id-based hashing).
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
- *frozen*: If true (the default is ``False``), assigning to fields will
|
2018-05-16 16:50:07 -03:00
|
|
|
generate an exception. This emulates read-only frozen instances. If
|
2023-04-24 20:26:18 -03:00
|
|
|
:meth:`~object.__setattr__` or :meth:`~object.__delattr__` is defined in the class, then
|
2018-05-16 16:50:07 -03:00
|
|
|
:exc:`TypeError` is raised. See the discussion below.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
- *match_args*: If true (the default is ``True``), the
|
|
|
|
:attr:`~object.__match_args__` tuple will be created from the list of
|
2023-04-24 20:26:18 -03:00
|
|
|
parameters to the generated :meth:`~object.__init__` method (even if
|
2024-03-21 16:47:09 -03:00
|
|
|
:meth:`!__init__` is not generated, see above). If false, or if
|
2024-04-14 13:29:01 -03:00
|
|
|
:attr:`!__match_args__` is already defined in the class, then
|
|
|
|
:attr:`!__match_args__` will not be generated.
|
2021-04-10 22:28:42 -03:00
|
|
|
|
2021-05-02 12:43:50 -03:00
|
|
|
.. versionadded:: 3.10
|
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
- *kw_only*: If true (the default value is ``False``), then all
|
2021-05-01 20:51:12 -03:00
|
|
|
fields will be marked as keyword-only. If a field is marked as
|
2023-04-24 20:26:18 -03:00
|
|
|
keyword-only, then the only effect is that the :meth:`~object.__init__`
|
2021-05-01 20:51:12 -03:00
|
|
|
parameter generated from a keyword-only field must be specified
|
2024-03-21 16:47:09 -03:00
|
|
|
with a keyword when :meth:`!__init__` is called. There is no
|
2021-05-01 20:51:12 -03:00
|
|
|
effect on any other aspect of dataclasses. See the
|
|
|
|
:term:`parameter` glossary entry for details. Also see the
|
2021-05-02 22:20:50 -03:00
|
|
|
:const:`KW_ONLY` section.
|
2021-04-10 22:28:42 -03:00
|
|
|
|
2021-05-02 12:43:50 -03:00
|
|
|
.. versionadded:: 3.10
|
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
- *slots*: If true (the default is ``False``), :attr:`~object.__slots__` attribute
|
2021-04-30 23:14:30 -03:00
|
|
|
will be generated and new class will be returned instead of the original one.
|
2024-03-21 16:47:09 -03:00
|
|
|
If :attr:`!__slots__` is already defined in the class, then :exc:`TypeError`
|
2021-04-30 23:14:30 -03:00
|
|
|
is raised.
|
|
|
|
|
2021-05-02 12:43:50 -03:00
|
|
|
.. versionadded:: 3.10
|
|
|
|
|
2022-03-19 18:01:17 -03:00
|
|
|
.. versionchanged:: 3.11
|
2024-04-14 13:29:01 -03:00
|
|
|
If a field name is already included in the :attr:`!__slots__`
|
|
|
|
of a base class, it will not be included in the generated :attr:`!__slots__`
|
2022-10-26 00:26:28 -03:00
|
|
|
to prevent :ref:`overriding them <datamodel-note-slots>`.
|
2024-04-14 13:29:01 -03:00
|
|
|
Therefore, do not use :attr:`!__slots__` to retrieve the field names of a
|
2022-03-19 18:01:17 -03:00
|
|
|
dataclass. Use :func:`fields` instead.
|
|
|
|
To be able to determine inherited slots,
|
2024-04-14 13:29:01 -03:00
|
|
|
base class :attr:`!__slots__` may be any iterable, but *not* an iterator.
|
2022-03-19 18:01:17 -03:00
|
|
|
|
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
- *weakref_slot*: If true (the default is ``False``), add a slot
|
2022-05-02 13:36:39 -03:00
|
|
|
named "__weakref__", which is required to make an instance
|
|
|
|
weakref-able. It is an error to specify ``weakref_slot=True``
|
|
|
|
without also specifying ``slots=True``.
|
|
|
|
|
|
|
|
.. versionadded:: 3.11
|
|
|
|
|
2018-05-16 05:20:43 -03:00
|
|
|
``field``\s may optionally specify a default value, using normal
|
|
|
|
Python syntax::
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class C:
|
|
|
|
a: int # 'a' has no default value
|
|
|
|
b: int = 0 # assign a default value for 'b'
|
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
In this example, both :attr:`!a` and :attr:`!b` will be included in the added
|
2023-04-24 20:26:18 -03:00
|
|
|
:meth:`~object.__init__` method, which will be defined as::
|
2018-05-16 05:20:43 -03:00
|
|
|
|
|
|
|
def __init__(self, a: int, b: int = 0):
|
|
|
|
|
|
|
|
:exc:`TypeError` will be raised if a field without a default value
|
2021-05-06 18:52:46 -03:00
|
|
|
follows a field with a default value. This is true whether this
|
2018-05-16 05:20:43 -03:00
|
|
|
occurs in a single class, or as a result of class inheritance.
|
|
|
|
|
2021-08-19 17:47:16 -03:00
|
|
|
.. function:: field(*, default=MISSING, default_factory=MISSING, init=True, repr=True, hash=None, compare=True, metadata=None, kw_only=MISSING)
|
2018-05-16 05:20:43 -03:00
|
|
|
|
|
|
|
For common and simple use cases, no other functionality is
|
2018-05-16 16:50:07 -03:00
|
|
|
required. There are, however, some dataclass features that
|
2018-05-16 05:20:43 -03:00
|
|
|
require additional per-field information. To satisfy this need for
|
|
|
|
additional information, you can replace the default field value
|
2024-03-21 16:47:09 -03:00
|
|
|
with a call to the provided :func:`!field` function. For example::
|
2018-05-16 05:20:43 -03:00
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class C:
|
2020-10-03 19:10:59 -03:00
|
|
|
mylist: list[int] = field(default_factory=list)
|
2018-05-16 05:20:43 -03:00
|
|
|
|
|
|
|
c = C()
|
2018-05-16 16:50:07 -03:00
|
|
|
c.mylist += [1, 2, 3]
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2021-05-02 22:20:50 -03:00
|
|
|
As shown above, the :const:`MISSING` value is a sentinel object used to
|
2021-09-02 13:03:22 -03:00
|
|
|
detect if some parameters are provided by the user. This sentinel is
|
|
|
|
used because ``None`` is a valid value for some parameters with
|
|
|
|
a distinct meaning. No code should directly use the :const:`MISSING` value.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
The parameters to :func:`!field` are:
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
- *default*: If provided, this will be the default value for this
|
2024-03-21 16:47:09 -03:00
|
|
|
field. This is needed because the :func:`!field` call itself
|
2018-05-16 05:20:43 -03:00
|
|
|
replaces the normal position of the default value.
|
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
- *default_factory*: If provided, it must be a zero-argument
|
2018-05-16 05:20:43 -03:00
|
|
|
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
|
2024-04-14 13:29:01 -03:00
|
|
|
error to specify both *default* and *default_factory*.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
- *init*: If true (the default), this field is included as a
|
2023-04-24 20:26:18 -03:00
|
|
|
parameter to the generated :meth:`~object.__init__` method.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
- *repr*: If true (the default), this field is included in the
|
2023-04-24 20:26:18 -03:00
|
|
|
string returned by the generated :meth:`~object.__repr__` method.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
- *hash*: This can be a bool or ``None``. If true, this field is
|
2023-04-24 20:26:18 -03:00
|
|
|
included in the generated :meth:`~object.__hash__` method. If ``None`` (the
|
2024-04-14 13:29:01 -03:00
|
|
|
default), use the value of *compare*: this would normally be
|
2018-05-16 05:20:43 -03:00
|
|
|
the expected behavior. A field should be considered in the hash
|
|
|
|
if it's used for comparisons. Setting this value to anything
|
|
|
|
other than ``None`` is discouraged.
|
|
|
|
|
|
|
|
One possible reason to set ``hash=False`` but ``compare=True``
|
|
|
|
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.
|
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
- *compare*: If true (the default), this field is included in the
|
2023-04-24 20:26:18 -03:00
|
|
|
generated equality and comparison methods (:meth:`~object.__eq__`,
|
|
|
|
:meth:`~object.__gt__`, et al.).
|
2021-05-01 20:51:12 -03:00
|
|
|
|
2024-05-08 16:35:16 -03:00
|
|
|
- *metadata*: This can be a mapping or ``None``. ``None`` is treated as
|
2018-05-16 05:20:43 -03:00
|
|
|
an empty dict. This value is wrapped in
|
|
|
|
:func:`~types.MappingProxyType` to make it read-only, and exposed
|
|
|
|
on the :class:`Field` 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.
|
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
- *kw_only*: If true, this field will be marked as keyword-only.
|
2023-04-24 20:26:18 -03:00
|
|
|
This is used when the generated :meth:`~object.__init__` method's
|
2021-05-01 20:51:12 -03:00
|
|
|
parameters are computed.
|
|
|
|
|
2021-05-02 12:43:50 -03:00
|
|
|
.. versionadded:: 3.10
|
|
|
|
|
2018-05-16 05:20:43 -03:00
|
|
|
If the default value of a field is specified by a call to
|
2024-03-21 16:47:09 -03:00
|
|
|
:func:`!field`, then the class attribute for this field will be
|
2024-04-14 13:29:01 -03:00
|
|
|
replaced by the specified *default* value. If *default* is not
|
2018-05-16 05:20:43 -03:00
|
|
|
provided, then the class attribute will be deleted. The intent is
|
2024-03-21 16:47:09 -03:00
|
|
|
that after the :func:`@dataclass <dataclass>` decorator runs, the class
|
2018-05-16 05:20:43 -03:00
|
|
|
attributes will all contain the default values for the fields, just
|
|
|
|
as if the default value itself were specified. For example,
|
|
|
|
after::
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class C:
|
|
|
|
x: int
|
|
|
|
y: int = field(repr=False)
|
|
|
|
z: int = field(repr=False, default=10)
|
|
|
|
t: int = 20
|
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
The class attribute :attr:`!C.z` will be ``10``, the class attribute
|
|
|
|
:attr:`!C.t` will be ``20``, and the class attributes :attr:`!C.x` and
|
|
|
|
:attr:`!C.y` will not be set.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
|
|
|
.. class:: Field
|
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
:class:`!Field` objects describe each defined field. These objects
|
2018-05-16 05:20:43 -03:00
|
|
|
are created internally, and are returned by the :func:`fields`
|
|
|
|
module-level method (see below). Users should never instantiate a
|
2024-03-21 16:47:09 -03:00
|
|
|
:class:`!Field` object directly. Its documented attributes are:
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
- :attr:`!name`: The name of the field.
|
|
|
|
- :attr:`!type`: The type of the field.
|
|
|
|
- :attr:`!default`, :attr:`!default_factory`, :attr:`!init`, :attr:`!repr`, :attr:`!hash`,
|
|
|
|
:attr:`!compare`, :attr:`!metadata`, and :attr:`!kw_only` have the identical
|
2023-10-11 17:43:03 -03:00
|
|
|
meaning and values as they do in the :func:`field` function.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
|
|
|
Other attributes may exist, but they are private and must not be
|
|
|
|
inspected or relied on.
|
|
|
|
|
|
|
|
.. function:: fields(class_or_instance)
|
|
|
|
|
2018-05-16 16:50:07 -03:00
|
|
|
Returns a tuple of :class:`Field` objects that define the fields for this
|
|
|
|
dataclass. Accepts either a dataclass, or an instance of a dataclass.
|
|
|
|
Raises :exc:`TypeError` if not passed a dataclass or instance of one.
|
|
|
|
Does not return pseudo-fields which are ``ClassVar`` or ``InitVar``.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2022-01-08 06:56:35 -04:00
|
|
|
.. function:: asdict(obj, *, dict_factory=dict)
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
Converts the dataclass *obj* to a dict (by using the
|
|
|
|
factory function *dict_factory*). Each dataclass is converted
|
2018-05-16 16:50:07 -03:00
|
|
|
to a dict of its fields, as ``name: value`` pairs. dataclasses, dicts,
|
2021-11-29 14:10:32 -04:00
|
|
|
lists, and tuples are recursed into. Other objects are copied with
|
|
|
|
:func:`copy.deepcopy`.
|
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
Example of using :func:`!asdict` on nested dataclasses::
|
2018-05-16 05:20:43 -03:00
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class Point:
|
|
|
|
x: int
|
|
|
|
y: int
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class C:
|
2020-10-03 19:10:59 -03:00
|
|
|
mylist: list[Point]
|
2018-05-16 05:20:43 -03:00
|
|
|
|
|
|
|
p = Point(10, 20)
|
|
|
|
assert asdict(p) == {'x': 10, 'y': 20}
|
|
|
|
|
|
|
|
c = C([Point(0, 0), Point(10, 4)])
|
2018-05-16 16:50:07 -03:00
|
|
|
assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2021-11-29 14:10:32 -04:00
|
|
|
To create a shallow copy, the following workaround may be used::
|
|
|
|
|
2024-04-13 21:14:43 -03:00
|
|
|
{field.name: getattr(obj, field.name) for field in fields(obj)}
|
2021-11-29 14:10:32 -04:00
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
:func:`!asdict` raises :exc:`TypeError` if *obj* is not a dataclass
|
2021-11-29 14:10:32 -04:00
|
|
|
instance.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2022-01-08 06:56:35 -04:00
|
|
|
.. function:: astuple(obj, *, tuple_factory=tuple)
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
Converts the dataclass *obj* to a tuple (by using the
|
|
|
|
factory function *tuple_factory*). Each dataclass is converted
|
2018-05-16 16:50:07 -03:00
|
|
|
to a tuple of its field values. dataclasses, dicts, lists, and
|
2021-11-29 14:10:32 -04:00
|
|
|
tuples are recursed into. Other objects are copied with
|
|
|
|
:func:`copy.deepcopy`.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
|
|
|
Continuing from the previous example::
|
|
|
|
|
|
|
|
assert astuple(p) == (10, 20)
|
|
|
|
assert astuple(c) == ([(0, 0), (10, 4)],)
|
|
|
|
|
2021-11-29 14:10:32 -04:00
|
|
|
To create a shallow copy, the following workaround may be used::
|
|
|
|
|
2022-01-08 06:56:35 -04:00
|
|
|
tuple(getattr(obj, field.name) for field in dataclasses.fields(obj))
|
2021-11-29 14:10:32 -04:00
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
:func:`!astuple` raises :exc:`TypeError` if *obj* is not a dataclass
|
2021-11-29 14:10:32 -04:00
|
|
|
instance.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2023-03-10 20:26:46 -04:00
|
|
|
.. 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)
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
Creates a new dataclass with name *cls_name*, fields as defined
|
|
|
|
in *fields*, base classes as given in *bases*, and initialized
|
|
|
|
with a namespace as given in *namespace*. *fields* is an
|
2018-05-16 05:20:43 -03:00
|
|
|
iterable whose elements are each either ``name``, ``(name, type)``,
|
|
|
|
or ``(name, type, Field)``. If just ``name`` is supplied,
|
2024-04-14 13:29:01 -03:00
|
|
|
:data:`typing.Any` is used for ``type``. The values of *init*,
|
|
|
|
*repr*, *eq*, *order*, *unsafe_hash*, *frozen*,
|
|
|
|
*match_args*, *kw_only*, *slots*, and *weakref_slot* have
|
2024-03-21 16:47:09 -03:00
|
|
|
the same meaning as they do in :func:`@dataclass <dataclass>`.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
If *module* is defined, the :attr:`!__module__` attribute
|
2023-03-10 20:26:46 -04:00
|
|
|
of the dataclass is set to that value.
|
|
|
|
By default, it is set to the module name of the caller.
|
|
|
|
|
2018-05-16 05:20:43 -03:00
|
|
|
This function is not strictly required, because any Python
|
2024-04-14 13:29:01 -03:00
|
|
|
mechanism for creating a new class with :attr:`!__annotations__` can
|
|
|
|
then apply the :func:`@dataclass <dataclass>` function to convert that class to
|
2018-05-16 16:50:07 -03:00
|
|
|
a dataclass. This function is provided as a convenience. For
|
2018-05-16 05:20:43 -03:00
|
|
|
example::
|
|
|
|
|
|
|
|
C = make_dataclass('C',
|
|
|
|
[('x', int),
|
|
|
|
'y',
|
|
|
|
('z', int, field(default=5))],
|
|
|
|
namespace={'add_one': lambda self: self.x + 1})
|
|
|
|
|
|
|
|
Is equivalent to::
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class C:
|
|
|
|
x: int
|
|
|
|
y: 'typing.Any'
|
|
|
|
z: int = 5
|
|
|
|
|
|
|
|
def add_one(self):
|
|
|
|
return self.x + 1
|
|
|
|
|
2022-01-08 06:56:35 -04:00
|
|
|
.. function:: replace(obj, /, **changes)
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
Creates a new object of the same type as *obj*, replacing
|
|
|
|
fields with values from *changes*. If *obj* is not a Data
|
|
|
|
Class, raises :exc:`TypeError`. If keys in *changes* are not
|
2024-04-13 21:03:09 -03:00
|
|
|
field names of the given dataclass, raises :exc:`TypeError`.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2023-04-24 20:26:18 -03:00
|
|
|
The newly returned object is created by calling the :meth:`~object.__init__`
|
2018-05-16 16:50:07 -03:00
|
|
|
method of the dataclass. This ensures that
|
2023-04-28 16:10:26 -03:00
|
|
|
:meth:`__post_init__`, if present, is also called.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
|
|
|
Init-only variables without default values, if any exist, must be
|
2024-03-21 16:47:09 -03:00
|
|
|
specified on the call to :func:`!replace` so that they can be passed to
|
|
|
|
:meth:`!__init__` and :meth:`__post_init__`.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
It is an error for *changes* to contain any fields that are
|
2018-05-16 05:20:43 -03:00
|
|
|
defined as having ``init=False``. A :exc:`ValueError` will be raised
|
|
|
|
in this case.
|
|
|
|
|
|
|
|
Be forewarned about how ``init=False`` fields work during a call to
|
2024-03-21 16:47:09 -03:00
|
|
|
:func:`!replace`. They are not copied from the source object, but
|
2023-04-28 16:10:26 -03:00
|
|
|
rather are initialized in :meth:`__post_init__`, if they're
|
2018-05-16 05:20:43 -03:00
|
|
|
initialized at all. It is expected that ``init=False`` fields will
|
|
|
|
be rarely and judiciously used. If they are used, it might be wise
|
|
|
|
to have alternate class constructors, or perhaps a custom
|
2024-04-14 13:29:01 -03:00
|
|
|
:func:`!replace` (or similarly named) method which handles instance
|
2018-05-16 05:20:43 -03:00
|
|
|
copying.
|
|
|
|
|
2023-09-06 17:55:42 -03:00
|
|
|
Dataclass instances are also supported by generic function :func:`copy.replace`.
|
|
|
|
|
2022-01-08 06:56:35 -04:00
|
|
|
.. function:: is_dataclass(obj)
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2019-11-12 10:57:03 -04:00
|
|
|
Return ``True`` if its parameter is a dataclass or an instance of one,
|
|
|
|
otherwise return ``False``.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
|
|
|
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 ``not
|
|
|
|
isinstance(obj, type)``::
|
|
|
|
|
|
|
|
def is_dataclass_instance(obj):
|
|
|
|
return is_dataclass(obj) and not isinstance(obj, type)
|
|
|
|
|
2021-05-02 22:20:50 -03:00
|
|
|
.. data:: MISSING
|
|
|
|
|
|
|
|
A sentinel value signifying a missing default or default_factory.
|
|
|
|
|
|
|
|
.. data:: KW_ONLY
|
|
|
|
|
2021-05-03 03:33:34 -03:00
|
|
|
A sentinel value used as a type annotation. Any fields after a
|
2024-03-21 16:47:09 -03:00
|
|
|
pseudo-field with the type of :const:`!KW_ONLY` are marked as
|
2021-05-02 22:20:50 -03:00
|
|
|
keyword-only fields. Note that a pseudo-field of type
|
2024-03-21 16:47:09 -03:00
|
|
|
:const:`!KW_ONLY` is otherwise completely ignored. This includes the
|
2021-05-03 01:07:29 -03:00
|
|
|
name of such a field. By convention, a name of ``_`` is used for a
|
2024-03-21 16:47:09 -03:00
|
|
|
:const:`!KW_ONLY` field. Keyword-only fields signify
|
2023-04-24 20:26:18 -03:00
|
|
|
:meth:`~object.__init__` parameters that must be specified as keywords when
|
2021-05-02 22:20:50 -03:00
|
|
|
the class is instantiated.
|
|
|
|
|
|
|
|
In this example, the fields ``y`` and ``z`` will be marked as keyword-only fields::
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class Point:
|
2022-10-29 14:06:52 -03:00
|
|
|
x: float
|
|
|
|
_: KW_ONLY
|
|
|
|
y: float
|
|
|
|
z: float
|
2021-05-02 22:20:50 -03:00
|
|
|
|
|
|
|
p = Point(0, y=1.5, z=2.0)
|
|
|
|
|
2021-05-03 02:55:13 -03:00
|
|
|
In a single dataclass, it is an error to specify more than one
|
2024-03-21 16:47:09 -03:00
|
|
|
field whose type is :const:`!KW_ONLY`.
|
2021-05-03 02:55:13 -03:00
|
|
|
|
2022-02-09 16:56:10 -04:00
|
|
|
.. versionadded:: 3.10
|
|
|
|
|
2021-05-02 22:20:50 -03:00
|
|
|
.. exception:: FrozenInstanceError
|
|
|
|
|
2023-04-24 20:26:18 -03:00
|
|
|
Raised when an implicitly defined :meth:`~object.__setattr__` or
|
|
|
|
:meth:`~object.__delattr__` is called on a dataclass which was defined with
|
2021-05-02 22:20:50 -03:00
|
|
|
``frozen=True``. It is a subclass of :exc:`AttributeError`.
|
|
|
|
|
2023-04-24 20:26:18 -03:00
|
|
|
.. _post-init-processing:
|
|
|
|
|
2018-05-16 05:20:43 -03:00
|
|
|
Post-init processing
|
|
|
|
--------------------
|
|
|
|
|
2023-04-28 16:10:26 -03:00
|
|
|
.. function:: __post_init__()
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2023-04-28 16:10:26 -03:00
|
|
|
When defined on the class, it will be called by the generated
|
2024-04-14 13:29:01 -03:00
|
|
|
:meth:`~object.__init__`, normally as :meth:`!self.__post_init__`.
|
2023-04-28 16:10:26 -03:00
|
|
|
However, if any ``InitVar`` fields are defined, they will also be
|
2024-03-21 16:47:09 -03:00
|
|
|
passed to :meth:`!__post_init__` in the order they were defined in the
|
|
|
|
class. If no :meth:`!__init__` method is generated, then
|
|
|
|
:meth:`!__post_init__` will not automatically be called.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2023-04-28 16:10:26 -03:00
|
|
|
Among other uses, this allows for initializing field values that
|
|
|
|
depend on one or more other fields. For example::
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2023-04-28 16:10:26 -03:00
|
|
|
@dataclass
|
|
|
|
class C:
|
|
|
|
a: float
|
|
|
|
b: float
|
|
|
|
c: float = field(init=False)
|
|
|
|
|
|
|
|
def __post_init__(self):
|
|
|
|
self.c = self.a + self.b
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
The :meth:`~object.__init__` method generated by :func:`@dataclass <dataclass>` does not call base
|
|
|
|
class :meth:`!__init__` methods. If the base class has an :meth:`!__init__` method
|
2021-05-10 10:30:22 -03:00
|
|
|
that has to be called, it is common to call this method in a
|
2023-04-28 16:10:26 -03:00
|
|
|
:meth:`__post_init__` method::
|
2021-05-10 10:30:22 -03:00
|
|
|
|
|
|
|
class Rectangle:
|
2024-01-16 21:17:34 -04:00
|
|
|
def __init__(self, height, width):
|
2024-01-28 16:10:32 -04:00
|
|
|
self.height = height
|
|
|
|
self.width = width
|
2021-05-10 10:30:22 -03:00
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class Square(Rectangle):
|
|
|
|
side: float
|
|
|
|
|
|
|
|
def __post_init__(self):
|
|
|
|
super().__init__(self.side, self.side)
|
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
Note, however, that in general the dataclass-generated :meth:`!__init__` methods
|
2021-05-10 10:30:22 -03:00
|
|
|
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.
|
|
|
|
|
2018-05-16 05:20:43 -03:00
|
|
|
See the section below on init-only variables for ways to pass
|
2024-03-21 16:47:09 -03:00
|
|
|
parameters to :meth:`!__post_init__`. Also see the warning about how
|
2018-05-16 05:20:43 -03:00
|
|
|
:func:`replace` handles ``init=False`` fields.
|
|
|
|
|
2024-04-14 05:03:16 -03:00
|
|
|
.. _dataclasses-class-variables:
|
|
|
|
|
2018-05-16 05:20:43 -03:00
|
|
|
Class variables
|
|
|
|
---------------
|
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
One of the few places where :func:`@dataclass <dataclass>` actually inspects the type
|
2018-05-16 05:20:43 -03:00
|
|
|
of a field is to determine if a field is a class variable as defined
|
|
|
|
in :pep:`526`. It does this by checking if the type of the field is
|
2024-04-14 13:29:01 -03:00
|
|
|
:data:`typing.ClassVar`. If a field is a ``ClassVar``, it is excluded
|
2018-05-16 16:50:07 -03:00
|
|
|
from consideration as a field and is ignored by the dataclass
|
2018-05-16 05:20:43 -03:00
|
|
|
mechanisms. Such ``ClassVar`` pseudo-fields are not returned by the
|
|
|
|
module-level :func:`fields` function.
|
|
|
|
|
2024-04-14 05:03:16 -03:00
|
|
|
.. _dataclasses-init-only-variables:
|
|
|
|
|
2018-05-16 05:20:43 -03:00
|
|
|
Init-only variables
|
|
|
|
-------------------
|
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
Another place where :func:`@dataclass <dataclass>` inspects a type annotation is to
|
2018-05-16 05:20:43 -03:00
|
|
|
determine if a field is an init-only variable. It does this by seeing
|
|
|
|
if the type of a field is of type ``dataclasses.InitVar``. If a field
|
|
|
|
is an ``InitVar``, 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 :func:`fields` function. Init-only fields are added as
|
2023-04-24 20:26:18 -03:00
|
|
|
parameters to the generated :meth:`~object.__init__` method, and are passed to
|
2023-04-28 16:10:26 -03:00
|
|
|
the optional :meth:`__post_init__` method. They are not otherwise used
|
2018-05-16 16:50:07 -03:00
|
|
|
by dataclasses.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2018-08-24 06:19:24 -03:00
|
|
|
For example, suppose a field will be initialized from a database, if a
|
2018-05-16 05:20:43 -03:00
|
|
|
value is not provided when creating the class::
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class C:
|
|
|
|
i: int
|
2022-10-31 12:02:02 -03:00
|
|
|
j: int | None = None
|
|
|
|
database: InitVar[DatabaseType | None] = None
|
2018-05-16 05:20:43 -03:00
|
|
|
|
|
|
|
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)
|
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
In this case, :func:`fields` will return :class:`Field` objects for :attr:`!i` and
|
|
|
|
:attr:`!j`, but not for :attr:`!database`.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-04-14 05:03:16 -03:00
|
|
|
.. _dataclasses-frozen:
|
|
|
|
|
2018-05-16 05:20:43 -03:00
|
|
|
Frozen instances
|
|
|
|
----------------
|
|
|
|
|
|
|
|
It is not possible to create truly immutable Python objects. However,
|
2024-03-21 16:47:09 -03:00
|
|
|
by passing ``frozen=True`` to the :func:`@dataclass <dataclass>` decorator you can
|
2018-05-16 16:50:07 -03:00
|
|
|
emulate immutability. In that case, dataclasses will add
|
2023-04-24 20:26:18 -03:00
|
|
|
:meth:`~object.__setattr__` and :meth:`~object.__delattr__` methods to the class. These
|
2018-05-16 05:20:43 -03:00
|
|
|
methods will raise a :exc:`FrozenInstanceError` when invoked.
|
|
|
|
|
|
|
|
There is a tiny performance penalty when using ``frozen=True``:
|
2023-04-24 20:26:18 -03:00
|
|
|
:meth:`~object.__init__` cannot use simple assignment to initialize fields, and
|
2024-05-16 10:39:37 -03:00
|
|
|
must use :meth:`!object.__setattr__`.
|
|
|
|
.. Make sure to not remove "object" from "object.__setattr__" in the above markup
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-04-14 05:03:16 -03:00
|
|
|
.. _dataclasses-inheritance:
|
|
|
|
|
2018-05-16 05:20:43 -03:00
|
|
|
Inheritance
|
|
|
|
-----------
|
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
When the dataclass is being created by the :func:`@dataclass <dataclass>` decorator,
|
2018-05-16 05:20:43 -03:00
|
|
|
it looks through all of the class's base classes in reverse MRO (that
|
2018-05-16 16:50:07 -03:00
|
|
|
is, starting at :class:`object`) and, for each dataclass that it finds,
|
2018-05-16 05:20:43 -03:00
|
|
|
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::
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class Base:
|
|
|
|
x: Any = 15.0
|
|
|
|
y: int = 0
|
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class C(Base):
|
|
|
|
z: int = 10
|
|
|
|
x: int = 15
|
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
The final list of fields is, in order, :attr:`!x`, :attr:`!y`, :attr:`!z`. The final
|
|
|
|
type of :attr:`!x` is :class:`int`, as specified in class :class:`!C`.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
The generated :meth:`~object.__init__` method for :class:`!C` will look like::
|
2018-05-16 05:20:43 -03:00
|
|
|
|
|
|
|
def __init__(self, x: int = 15, y: int = 0, z: int = 10):
|
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
Re-ordering of keyword-only parameters in :meth:`!__init__`
|
|
|
|
-----------------------------------------------------------
|
2021-04-25 21:42:39 -03:00
|
|
|
|
2023-04-24 20:26:18 -03:00
|
|
|
After the parameters needed for :meth:`~object.__init__` are computed, any
|
2021-05-01 22:46:05 -03:00
|
|
|
keyword-only parameters are moved to come after all regular
|
2021-05-03 02:55:13 -03:00
|
|
|
(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.
|
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
In this example, :attr:`!Base.y`, :attr:`!Base.w`, and :attr:`!D.t` are keyword-only
|
|
|
|
fields, and :attr:`!Base.x` and :attr:`!D.z` are regular fields::
|
2021-04-25 21:42:39 -03:00
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class Base:
|
|
|
|
x: Any = 15.0
|
|
|
|
_: KW_ONLY
|
|
|
|
y: int = 0
|
2021-05-01 20:51:12 -03:00
|
|
|
w: int = 1
|
2021-04-25 21:42:39 -03:00
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class D(Base):
|
|
|
|
z: int = 10
|
|
|
|
t: int = field(kw_only=True, default=0)
|
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
The generated :meth:`!__init__` method for :class:`!D` will look like::
|
2021-04-25 21:42:39 -03:00
|
|
|
|
2021-05-01 20:51:12 -03:00
|
|
|
def __init__(self, x: Any = 15.0, z: int = 10, *, y: int = 0, w: int = 1, t: int = 0):
|
|
|
|
|
|
|
|
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.
|
2021-04-25 21:42:39 -03:00
|
|
|
|
2021-05-01 22:46:05 -03:00
|
|
|
The relative ordering of keyword-only parameters is maintained in the
|
2024-03-21 16:47:09 -03:00
|
|
|
re-ordered :meth:`!__init__` parameter list.
|
2021-04-25 21:42:39 -03:00
|
|
|
|
|
|
|
|
2018-05-16 05:20:43 -03:00
|
|
|
Default factory functions
|
|
|
|
-------------------------
|
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
If a :func:`field` specifies a *default_factory*, it is called with
|
2021-12-12 14:05:48 -04:00
|
|
|
zero arguments when a default value for the field is needed. For
|
|
|
|
example, to create a new instance of a list, use::
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2021-12-12 14:05:48 -04:00
|
|
|
mylist: list = field(default_factory=list)
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2023-04-24 20:26:18 -03:00
|
|
|
If a field is excluded from :meth:`~object.__init__` (using ``init=False``)
|
2024-04-14 13:29:01 -03:00
|
|
|
and the field also specifies *default_factory*, then the default
|
2021-12-12 14:05:48 -04:00
|
|
|
factory function will always be called from the generated
|
2024-03-21 16:47:09 -03:00
|
|
|
:meth:`!__init__` function. This happens because there is no other
|
2021-12-12 14:05:48 -04:00
|
|
|
way to give the field an initial value.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
|
|
|
Mutable default values
|
|
|
|
----------------------
|
|
|
|
|
2021-12-12 14:05:48 -04:00
|
|
|
Python stores default member variable values in class attributes.
|
|
|
|
Consider this example, not using dataclasses::
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2021-12-12 14:05:48 -04:00
|
|
|
class C:
|
|
|
|
x = []
|
|
|
|
def add(self, element):
|
|
|
|
self.x.append(element)
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2021-12-12 14:05:48 -04:00
|
|
|
o1 = C()
|
|
|
|
o2 = C()
|
|
|
|
o1.add(1)
|
|
|
|
o2.add(2)
|
|
|
|
assert o1.x == [1, 2]
|
|
|
|
assert o1.x is o2.x
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
Note that the two instances of class :class:`!C` share the same class
|
|
|
|
variable :attr:`!x`, as expected.
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2021-12-12 14:05:48 -04:00
|
|
|
Using dataclasses, *if* this code was valid::
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2021-12-12 14:05:48 -04:00
|
|
|
@dataclass
|
|
|
|
class D:
|
2023-04-24 14:16:23 -03:00
|
|
|
x: list = [] # This code raises ValueError
|
2021-12-12 14:05:48 -04:00
|
|
|
def add(self, element):
|
2024-03-09 17:52:57 -04:00
|
|
|
self.x.append(element)
|
2021-12-12 14:05:48 -04:00
|
|
|
|
|
|
|
it would generate code similar to::
|
|
|
|
|
|
|
|
class D:
|
|
|
|
x = []
|
|
|
|
def __init__(self, x=x):
|
|
|
|
self.x = x
|
|
|
|
def add(self, element):
|
2024-03-09 17:52:57 -04:00
|
|
|
self.x.append(element)
|
2021-12-12 14:05:48 -04:00
|
|
|
|
|
|
|
assert D().x is D().x
|
|
|
|
|
2024-04-14 13:29:01 -03:00
|
|
|
This has the same issue as the original example using class :class:`!C`.
|
|
|
|
That is, two instances of class :class:`!D` that do not specify a value
|
|
|
|
for :attr:`!x` when creating a class instance will share the same copy
|
|
|
|
of :attr:`!x`. Because dataclasses just use normal Python class
|
2021-12-12 14:05:48 -04:00
|
|
|
creation they also share this behavior. There is no general way
|
|
|
|
for Data Classes to detect this condition. Instead, the
|
2024-03-21 16:47:09 -03:00
|
|
|
:func:`@dataclass <dataclass>` decorator will raise a :exc:`ValueError` if it
|
2021-12-12 14:05:48 -04:00
|
|
|
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.
|
|
|
|
|
|
|
|
Using default factory functions is a way to create new instances of
|
|
|
|
mutable types as default values for fields::
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2021-12-12 14:05:48 -04:00
|
|
|
@dataclass
|
|
|
|
class D:
|
|
|
|
x: list = field(default_factory=list)
|
2018-05-16 05:20:43 -03:00
|
|
|
|
2021-12-12 14:05:48 -04:00
|
|
|
assert D().x is not D().x
|
2021-12-11 17:12:17 -04:00
|
|
|
|
2021-12-12 14:05:48 -04:00
|
|
|
.. versionchanged:: 3.11
|
2024-04-14 13:29:01 -03:00
|
|
|
Instead of looking for and disallowing objects of type :class:`list`,
|
|
|
|
:class:`dict`, or :class:`set`, unhashable objects are now not allowed as
|
2021-12-12 14:05:48 -04:00
|
|
|
default values. Unhashability is used to approximate
|
|
|
|
mutability.
|
2022-07-05 15:09:41 -03:00
|
|
|
|
|
|
|
Descriptor-typed fields
|
|
|
|
-----------------------
|
|
|
|
|
|
|
|
Fields that are assigned :ref:`descriptor objects <descriptors>` as their
|
|
|
|
default value have the following special behaviors:
|
|
|
|
|
2024-03-21 16:47:09 -03:00
|
|
|
* The value for the field passed to the dataclass's :meth:`~object.__init__` method is
|
|
|
|
passed to the descriptor's :meth:`~object.__set__` method rather than overwriting the
|
2022-07-05 15:09:41 -03:00
|
|
|
descriptor object.
|
2024-03-21 16:47:09 -03:00
|
|
|
|
2022-07-05 15:09:41 -03:00
|
|
|
* Similarly, when getting or setting the field, the descriptor's
|
2024-03-21 16:47:09 -03:00
|
|
|
:meth:`~object.__get__` or :meth:`!__set__` method is called rather than returning or
|
2022-07-05 15:09:41 -03:00
|
|
|
overwriting the descriptor object.
|
2024-03-21 16:47:09 -03:00
|
|
|
|
|
|
|
* To determine whether a field contains a default value, :func:`@dataclass <dataclass>`
|
|
|
|
will call the descriptor's :meth:`!__get__` method using its class access
|
|
|
|
form: ``descriptor.__get__(obj=None, type=cls)``. If the
|
2022-07-05 15:09:41 -03:00
|
|
|
descriptor returns a value in this case, it will be used as the
|
|
|
|
field's default. On the other hand, if the descriptor raises
|
|
|
|
:exc:`AttributeError` in this situation, no default value will be
|
|
|
|
provided for the field.
|
|
|
|
|
|
|
|
::
|
|
|
|
|
|
|
|
class IntConversionDescriptor:
|
2022-10-29 14:06:52 -03:00
|
|
|
def __init__(self, *, default):
|
|
|
|
self._default = default
|
2022-07-05 15:09:41 -03:00
|
|
|
|
2022-10-29 14:06:52 -03:00
|
|
|
def __set_name__(self, owner, name):
|
|
|
|
self._name = "_" + name
|
2022-07-05 15:09:41 -03:00
|
|
|
|
2022-10-29 14:06:52 -03:00
|
|
|
def __get__(self, obj, type):
|
|
|
|
if obj is None:
|
|
|
|
return self._default
|
2022-07-05 15:09:41 -03:00
|
|
|
|
2022-10-29 14:06:52 -03:00
|
|
|
return getattr(obj, self._name, self._default)
|
2022-07-05 15:09:41 -03:00
|
|
|
|
2022-10-29 14:06:52 -03:00
|
|
|
def __set__(self, obj, value):
|
|
|
|
setattr(obj, self._name, int(value))
|
2022-07-05 15:09:41 -03:00
|
|
|
|
|
|
|
@dataclass
|
|
|
|
class InventoryItem:
|
2022-10-29 14:06:52 -03:00
|
|
|
quantity_on_hand: IntConversionDescriptor = IntConversionDescriptor(default=100)
|
2022-07-05 15:09:41 -03:00
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
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.
|