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