| Eric V. Smith | 7a1c027 | 2018-05-16 09:29:05 -0400 | [diff] [blame] | 1 | :mod:`dataclasses` --- Data Classes |
| 2 | =================================== |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 3 | |
| 4 | .. module:: dataclasses |
| Eric V. Smith | 7a1c027 | 2018-05-16 09:29:05 -0400 | [diff] [blame] | 5 | :synopsis: Generate special methods on user-defined classes. |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 6 | |
| 7 | .. moduleauthor:: Eric V. Smith <eric@trueblade.com> |
| 8 | .. sectionauthor:: Eric V. Smith <eric@trueblade.com> |
| 9 | |
| 10 | **Source code:** :source:`Lib/dataclasses.py` |
| 11 | |
| 12 | -------------- |
| 13 | |
| 14 | This module provides a decorator and functions for automatically |
| 15 | adding generated :term:`special method`\s such as :meth:`__init__` and |
| 16 | :meth:`__repr__` to user-defined classes. It was originally described |
| 17 | in :pep:`557`. |
| 18 | |
| 19 | The member variables to use in these generated methods are defined |
| 20 | using :pep:`526` type annotations. For example this code:: |
| 21 | |
| Ned Batchelder | 2effef7 | 2020-05-08 07:39:57 -0400 | [diff] [blame] | 22 | from dataclasses import dataclass |
| 23 | |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 24 | @dataclass |
| 25 | class InventoryItem: |
| marload | 61bb24a | 2020-07-09 21:13:47 +0900 | [diff] [blame] | 26 | """Class for keeping track of an item in inventory.""" |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 27 | name: str |
| 28 | unit_price: float |
| 29 | quantity_on_hand: int = 0 |
| 30 | |
| 31 | def total_cost(self) -> float: |
| 32 | return self.unit_price * self.quantity_on_hand |
| 33 | |
| 34 | Will add, among other things, a :meth:`__init__` that looks like:: |
| 35 | |
| Mohamed Moselhy | e726a90 | 2021-04-30 19:06:55 -0400 | [diff] [blame] | 36 | def __init__(self, name: str, unit_price: float, quantity_on_hand: int = 0): |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 37 | self.name = name |
| 38 | self.unit_price = unit_price |
| 39 | self.quantity_on_hand = quantity_on_hand |
| 40 | |
| 41 | Note that this method is automatically added to the class: it is not |
| 42 | directly specified in the ``InventoryItem`` definition shown above. |
| 43 | |
| 44 | .. versionadded:: 3.7 |
| 45 | |
| 46 | Module-level decorators, classes, and functions |
| 47 | ----------------------------------------------- |
| 48 | |
| Yurii Karabas | c241991 | 2021-05-01 05:14:30 +0300 | [diff] [blame^] | 49 | .. decorator:: dataclass(*, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False) |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 50 | |
| 51 | This function is a :term:`decorator` that is used to add generated |
| 52 | :term:`special method`\s to classes, as described below. |
| 53 | |
| 54 | The :func:`dataclass` decorator examines the class to find |
| 55 | ``field``\s. A ``field`` is defined as class variable that has a |
| Cheryl Sabella | b7105c9 | 2018-12-24 00:09:09 -0500 | [diff] [blame] | 56 | :term:`type annotation <variable annotation>`. With two |
| 57 | exceptions described below, nothing in :func:`dataclass` |
| 58 | examines the type specified in the variable annotation. |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 59 | |
| 60 | The order of the fields in all of the generated methods is the |
| 61 | order in which they appear in the class definition. |
| 62 | |
| 63 | The :func:`dataclass` decorator will add various "dunder" methods to |
| 64 | the class, described below. If any of the added methods already |
| Fabio Sangiovanni | e28aff5 | 2019-12-25 23:45:30 +0100 | [diff] [blame] | 65 | exist on the class, the behavior depends on the parameter, as documented |
| 66 | below. The decorator returns the same class that is called on; no new |
| 67 | class is created. |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 68 | |
| 69 | If :func:`dataclass` is used just as a simple decorator with no parameters, |
| 70 | it acts as if it has the default values documented in this |
| 71 | signature. That is, these three uses of :func:`dataclass` are |
| 72 | equivalent:: |
| 73 | |
| 74 | @dataclass |
| 75 | class C: |
| 76 | ... |
| 77 | |
| 78 | @dataclass() |
| 79 | class C: |
| 80 | ... |
| 81 | |
| Yurii Karabas | c241991 | 2021-05-01 05:14:30 +0300 | [diff] [blame^] | 82 | @dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False) |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 83 | class C: |
| 84 | ... |
| 85 | |
| 86 | The parameters to :func:`dataclass` are: |
| 87 | |
| 88 | - ``init``: If true (the default), a :meth:`__init__` method will be |
| 89 | generated. |
| 90 | |
| 91 | If the class already defines :meth:`__init__`, this parameter is |
| 92 | ignored. |
| 93 | |
| 94 | - ``repr``: If true (the default), a :meth:`__repr__` method will be |
| 95 | generated. The generated repr string will have the class name and |
| 96 | the name and repr of each field, in the order they are defined in |
| 97 | the class. Fields that are marked as being excluded from the repr |
| 98 | are not included. For example: |
| 99 | ``InventoryItem(name='widget', unit_price=3.0, quantity_on_hand=10)``. |
| 100 | |
| 101 | If the class already defines :meth:`__repr__`, this parameter is |
| 102 | ignored. |
| 103 | |
| 104 | - ``eq``: If true (the default), an :meth:`__eq__` method will be |
| 105 | generated. This method compares the class as if it were a tuple |
| 106 | of its fields, in order. Both instances in the comparison must |
| 107 | be of the identical type. |
| 108 | |
| 109 | If the class already defines :meth:`__eq__`, this parameter is |
| 110 | ignored. |
| 111 | |
| 112 | - ``order``: If true (the default is ``False``), :meth:`__lt__`, |
| 113 | :meth:`__le__`, :meth:`__gt__`, and :meth:`__ge__` methods will be |
| 114 | generated. These compare the class as if it were a tuple of its |
| 115 | fields, in order. Both instances in the comparison must be of the |
| 116 | identical type. If ``order`` is true and ``eq`` is false, a |
| 117 | :exc:`ValueError` is raised. |
| 118 | |
| 119 | If the class already defines any of :meth:`__lt__`, |
| 120 | :meth:`__le__`, :meth:`__gt__`, or :meth:`__ge__`, then |
| Fabio Sangiovanni | e28aff5 | 2019-12-25 23:45:30 +0100 | [diff] [blame] | 121 | :exc:`TypeError` is raised. |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 122 | |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 123 | - ``unsafe_hash``: If ``False`` (the default), a :meth:`__hash__` method |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 124 | is generated according to how ``eq`` and ``frozen`` are set. |
| 125 | |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 126 | :meth:`__hash__` is used by built-in :meth:`hash()`, and when objects are |
| 127 | added to hashed collections such as dictionaries and sets. Having a |
| 128 | :meth:`__hash__` implies that instances of the class are immutable. |
| 129 | Mutability is a complicated property that depends on the programmer's |
| 130 | intent, the existence and behavior of :meth:`__eq__`, and the values of |
| 131 | the ``eq`` and ``frozen`` flags in the :func:`dataclass` decorator. |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 132 | |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 133 | By default, :func:`dataclass` will not implicitly add a :meth:`__hash__` |
| 134 | method unless it is safe to do so. Neither will it add or change an |
| 135 | existing explicitly defined :meth:`__hash__` method. Setting the class |
| 136 | attribute ``__hash__ = None`` has a specific meaning to Python, as |
| 137 | described in the :meth:`__hash__` documentation. |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 138 | |
| Guilherme Martins Crocetti | 0554044 | 2021-03-08 19:50:39 -0300 | [diff] [blame] | 139 | If :meth:`__hash__` is not explicitly defined, or if it is set to ``None``, |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 140 | then :func:`dataclass` *may* add an implicit :meth:`__hash__` method. |
| 141 | Although not recommended, you can force :func:`dataclass` to create a |
| 142 | :meth:`__hash__` method with ``unsafe_hash=True``. This might be the case |
| 143 | if your class is logically immutable but can nonetheless be mutated. |
| 144 | This is a specialized use case and should be considered carefully. |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 145 | |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 146 | Here are the rules governing implicit creation of a :meth:`__hash__` |
| 147 | method. Note that you cannot both have an explicit :meth:`__hash__` |
| 148 | method in your dataclass and set ``unsafe_hash=True``; this will result |
| 149 | in a :exc:`TypeError`. |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 150 | |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 151 | If ``eq`` and ``frozen`` are both true, by default :func:`dataclass` will |
| 152 | generate a :meth:`__hash__` method for you. If ``eq`` is true and |
| 153 | ``frozen`` is false, :meth:`__hash__` will be set to ``None``, marking it |
| 154 | unhashable (which it is, since it is mutable). If ``eq`` is false, |
| 155 | :meth:`__hash__` will be left untouched meaning the :meth:`__hash__` |
| 156 | method of the superclass will be used (if the superclass is |
| 157 | :class:`object`, this means it will fall back to id-based hashing). |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 158 | |
| Serhiy Storchaka | 138ccbb | 2019-11-12 16:57:03 +0200 | [diff] [blame] | 159 | - ``frozen``: If true (the default is ``False``), assigning to fields will |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 160 | generate an exception. This emulates read-only frozen instances. If |
| 161 | :meth:`__setattr__` or :meth:`__delattr__` is defined in the class, then |
| 162 | :exc:`TypeError` is raised. See the discussion below. |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 163 | |
| Eric V. Smith | 750f484 | 2021-04-10 21:28:42 -0400 | [diff] [blame] | 164 | - ``match_args``: If true (the default is ``True``), the |
| 165 | ``__match_args__`` tuple will be created from the list of |
| 166 | parameters to the generated :meth:`__init__` method (even if |
| 167 | :meth:`__init__` is not generated, see above). If false, or if |
| 168 | ``__match_args__`` is already defined in the class, then |
| 169 | ``__match_args__`` will not be generated. |
| 170 | |
| Eric V. Smith | c028053 | 2021-04-25 20:42:39 -0400 | [diff] [blame] | 171 | - ``kw_only``: If true (the default value is ``False``), then all |
| 172 | fields will be marked as keyword-only. See the :term:`parameter` |
| 173 | glossary entry for details. Also see the ``dataclasses.KW_ONLY`` |
| 174 | section. |
| Eric V. Smith | 750f484 | 2021-04-10 21:28:42 -0400 | [diff] [blame] | 175 | |
| Yurii Karabas | c241991 | 2021-05-01 05:14:30 +0300 | [diff] [blame^] | 176 | - ``slots``: If true (the default is ``False``), :attr:`__slots__` attribute |
| 177 | will be generated and new class will be returned instead of the original one. |
| 178 | If :attr:`__slots__` is already defined in the class, then :exc:`TypeError` |
| 179 | is raised. |
| 180 | |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 181 | ``field``\s may optionally specify a default value, using normal |
| 182 | Python syntax:: |
| 183 | |
| 184 | @dataclass |
| 185 | class C: |
| 186 | a: int # 'a' has no default value |
| 187 | b: int = 0 # assign a default value for 'b' |
| 188 | |
| 189 | In this example, both ``a`` and ``b`` will be included in the added |
| 190 | :meth:`__init__` method, which will be defined as:: |
| 191 | |
| 192 | def __init__(self, a: int, b: int = 0): |
| 193 | |
| 194 | :exc:`TypeError` will be raised if a field without a default value |
| 195 | follows a field with a default value. This is true either when this |
| 196 | occurs in a single class, or as a result of class inheritance. |
| 197 | |
| 198 | .. function:: field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata=None) |
| 199 | |
| 200 | For common and simple use cases, no other functionality is |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 201 | required. There are, however, some dataclass features that |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 202 | require additional per-field information. To satisfy this need for |
| 203 | additional information, you can replace the default field value |
| 204 | with a call to the provided :func:`field` function. For example:: |
| 205 | |
| 206 | @dataclass |
| 207 | class C: |
| Andre Delfino | 7f54e56 | 2020-10-03 19:10:59 -0300 | [diff] [blame] | 208 | mylist: list[int] = field(default_factory=list) |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 209 | |
| 210 | c = C() |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 211 | c.mylist += [1, 2, 3] |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 212 | |
| 213 | As shown above, the ``MISSING`` value is a sentinel object used to |
| 214 | detect if the ``default`` and ``default_factory`` parameters are |
| 215 | provided. This sentinel is used because ``None`` is a valid value |
| 216 | for ``default``. No code should directly use the ``MISSING`` |
| 217 | value. |
| 218 | |
| 219 | The parameters to :func:`field` are: |
| 220 | |
| 221 | - ``default``: If provided, this will be the default value for this |
| 222 | field. This is needed because the :meth:`field` call itself |
| 223 | replaces the normal position of the default value. |
| 224 | |
| 225 | - ``default_factory``: If provided, it must be a zero-argument |
| 226 | callable that will be called when a default value is needed for |
| 227 | this field. Among other purposes, this can be used to specify |
| 228 | fields with mutable default values, as discussed below. It is an |
| 229 | error to specify both ``default`` and ``default_factory``. |
| 230 | |
| 231 | - ``init``: If true (the default), this field is included as a |
| 232 | parameter to the generated :meth:`__init__` method. |
| 233 | |
| 234 | - ``repr``: If true (the default), this field is included in the |
| 235 | string returned by the generated :meth:`__repr__` method. |
| 236 | |
| 237 | - ``compare``: If true (the default), this field is included in the |
| 238 | generated equality and comparison methods (:meth:`__eq__`, |
| 239 | :meth:`__gt__`, et al.). |
| 240 | |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 241 | - ``hash``: This can be a bool or ``None``. If true, this field is |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 242 | included in the generated :meth:`__hash__` method. If ``None`` (the |
| 243 | default), use the value of ``compare``: this would normally be |
| 244 | the expected behavior. A field should be considered in the hash |
| 245 | if it's used for comparisons. Setting this value to anything |
| 246 | other than ``None`` is discouraged. |
| 247 | |
| 248 | One possible reason to set ``hash=False`` but ``compare=True`` |
| 249 | would be if a field is expensive to compute a hash value for, |
| 250 | that field is needed for equality testing, and there are other |
| 251 | fields that contribute to the type's hash value. Even if a field |
| 252 | is excluded from the hash, it will still be used for comparisons. |
| 253 | |
| 254 | - ``metadata``: This can be a mapping or None. None is treated as |
| 255 | an empty dict. This value is wrapped in |
| 256 | :func:`~types.MappingProxyType` to make it read-only, and exposed |
| 257 | on the :class:`Field` object. It is not used at all by Data |
| 258 | Classes, and is provided as a third-party extension mechanism. |
| 259 | Multiple third-parties can each have their own key, to use as a |
| 260 | namespace in the metadata. |
| 261 | |
| 262 | If the default value of a field is specified by a call to |
| 263 | :func:`field()`, then the class attribute for this field will be |
| 264 | replaced by the specified ``default`` value. If no ``default`` is |
| 265 | provided, then the class attribute will be deleted. The intent is |
| 266 | that after the :func:`dataclass` decorator runs, the class |
| 267 | attributes will all contain the default values for the fields, just |
| 268 | as if the default value itself were specified. For example, |
| 269 | after:: |
| 270 | |
| 271 | @dataclass |
| 272 | class C: |
| 273 | x: int |
| 274 | y: int = field(repr=False) |
| 275 | z: int = field(repr=False, default=10) |
| 276 | t: int = 20 |
| 277 | |
| 278 | The class attribute ``C.z`` will be ``10``, the class attribute |
| 279 | ``C.t`` will be ``20``, and the class attributes ``C.x`` and |
| 280 | ``C.y`` will not be set. |
| 281 | |
| 282 | .. class:: Field |
| 283 | |
| 284 | :class:`Field` objects describe each defined field. These objects |
| 285 | are created internally, and are returned by the :func:`fields` |
| 286 | module-level method (see below). Users should never instantiate a |
| 287 | :class:`Field` object directly. Its documented attributes are: |
| 288 | |
| 289 | - ``name``: The name of the field. |
| 290 | |
| 291 | - ``type``: The type of the field. |
| 292 | |
| 293 | - ``default``, ``default_factory``, ``init``, ``repr``, ``hash``, |
| 294 | ``compare``, and ``metadata`` have the identical meaning and |
| 295 | values as they do in the :func:`field` declaration. |
| 296 | |
| 297 | Other attributes may exist, but they are private and must not be |
| 298 | inspected or relied on. |
| 299 | |
| 300 | .. function:: fields(class_or_instance) |
| 301 | |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 302 | Returns a tuple of :class:`Field` objects that define the fields for this |
| 303 | dataclass. Accepts either a dataclass, or an instance of a dataclass. |
| 304 | Raises :exc:`TypeError` if not passed a dataclass or instance of one. |
| 305 | Does not return pseudo-fields which are ``ClassVar`` or ``InitVar``. |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 306 | |
| 307 | .. function:: asdict(instance, *, dict_factory=dict) |
| 308 | |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 309 | Converts the dataclass ``instance`` to a dict (by using the |
| 310 | factory function ``dict_factory``). Each dataclass is converted |
| 311 | to a dict of its fields, as ``name: value`` pairs. dataclasses, dicts, |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 312 | lists, and tuples are recursed into. For example:: |
| 313 | |
| 314 | @dataclass |
| 315 | class Point: |
| 316 | x: int |
| 317 | y: int |
| 318 | |
| 319 | @dataclass |
| 320 | class C: |
| Andre Delfino | 7f54e56 | 2020-10-03 19:10:59 -0300 | [diff] [blame] | 321 | mylist: list[Point] |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 322 | |
| 323 | p = Point(10, 20) |
| 324 | assert asdict(p) == {'x': 10, 'y': 20} |
| 325 | |
| 326 | c = C([Point(0, 0), Point(10, 4)]) |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 327 | assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]} |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 328 | |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 329 | Raises :exc:`TypeError` if ``instance`` is not a dataclass instance. |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 330 | |
| 방성범 (Bang Seongbeom) | 508d820 | 2018-09-29 19:50:31 +0900 | [diff] [blame] | 331 | .. function:: astuple(instance, *, tuple_factory=tuple) |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 332 | |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 333 | Converts the dataclass ``instance`` to a tuple (by using the |
| 334 | factory function ``tuple_factory``). Each dataclass is converted |
| 335 | to a tuple of its field values. dataclasses, dicts, lists, and |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 336 | tuples are recursed into. |
| 337 | |
| 338 | Continuing from the previous example:: |
| 339 | |
| 340 | assert astuple(p) == (10, 20) |
| 341 | assert astuple(c) == ([(0, 0), (10, 4)],) |
| 342 | |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 343 | Raises :exc:`TypeError` if ``instance`` is not a dataclass instance. |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 344 | |
| Yurii Karabas | c241991 | 2021-05-01 05:14:30 +0300 | [diff] [blame^] | 345 | .. 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) |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 346 | |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 347 | Creates a new dataclass with name ``cls_name``, fields as defined |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 348 | in ``fields``, base classes as given in ``bases``, and initialized |
| 349 | with a namespace as given in ``namespace``. ``fields`` is an |
| 350 | iterable whose elements are each either ``name``, ``(name, type)``, |
| 351 | or ``(name, type, Field)``. If just ``name`` is supplied, |
| 352 | ``typing.Any`` is used for ``type``. The values of ``init``, |
| Eric V. Smith | c028053 | 2021-04-25 20:42:39 -0400 | [diff] [blame] | 353 | ``repr``, ``eq``, ``order``, ``unsafe_hash``, ``frozen``, |
| Yurii Karabas | c241991 | 2021-05-01 05:14:30 +0300 | [diff] [blame^] | 354 | ``match_args``, ``kw_only``, and ``slots`` have the same meaning as |
| 355 | they do in :func:`dataclass`. |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 356 | |
| 357 | This function is not strictly required, because any Python |
| 358 | mechanism for creating a new class with ``__annotations__`` can |
| 359 | then apply the :func:`dataclass` function to convert that class to |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 360 | a dataclass. This function is provided as a convenience. For |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 361 | example:: |
| 362 | |
| 363 | C = make_dataclass('C', |
| 364 | [('x', int), |
| 365 | 'y', |
| 366 | ('z', int, field(default=5))], |
| 367 | namespace={'add_one': lambda self: self.x + 1}) |
| 368 | |
| 369 | Is equivalent to:: |
| 370 | |
| 371 | @dataclass |
| 372 | class C: |
| 373 | x: int |
| 374 | y: 'typing.Any' |
| 375 | z: int = 5 |
| 376 | |
| 377 | def add_one(self): |
| 378 | return self.x + 1 |
| 379 | |
| Serhiy Storchaka | 2d88e63 | 2019-06-26 19:07:44 +0300 | [diff] [blame] | 380 | .. function:: replace(instance, /, **changes) |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 381 | |
| 382 | Creates a new object of the same type of ``instance``, replacing |
| 383 | fields with values from ``changes``. If ``instance`` is not a Data |
| 384 | Class, raises :exc:`TypeError`. If values in ``changes`` do not |
| 385 | specify fields, raises :exc:`TypeError`. |
| 386 | |
| 387 | The newly returned object is created by calling the :meth:`__init__` |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 388 | method of the dataclass. This ensures that |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 389 | :meth:`__post_init__`, if present, is also called. |
| 390 | |
| 391 | Init-only variables without default values, if any exist, must be |
| 392 | specified on the call to :func:`replace` so that they can be passed to |
| 393 | :meth:`__init__` and :meth:`__post_init__`. |
| 394 | |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 395 | It is an error for ``changes`` to contain any fields that are |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 396 | defined as having ``init=False``. A :exc:`ValueError` will be raised |
| 397 | in this case. |
| 398 | |
| 399 | Be forewarned about how ``init=False`` fields work during a call to |
| 400 | :func:`replace`. They are not copied from the source object, but |
| 401 | rather are initialized in :meth:`__post_init__`, if they're |
| 402 | initialized at all. It is expected that ``init=False`` fields will |
| 403 | be rarely and judiciously used. If they are used, it might be wise |
| 404 | to have alternate class constructors, or perhaps a custom |
| 405 | ``replace()`` (or similarly named) method which handles instance |
| 406 | copying. |
| 407 | |
| 408 | .. function:: is_dataclass(class_or_instance) |
| 409 | |
| Serhiy Storchaka | 138ccbb | 2019-11-12 16:57:03 +0200 | [diff] [blame] | 410 | Return ``True`` if its parameter is a dataclass or an instance of one, |
| 411 | otherwise return ``False``. |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 412 | |
| 413 | If you need to know if a class is an instance of a dataclass (and |
| 414 | not a dataclass itself), then add a further check for ``not |
| 415 | isinstance(obj, type)``:: |
| 416 | |
| 417 | def is_dataclass_instance(obj): |
| 418 | return is_dataclass(obj) and not isinstance(obj, type) |
| 419 | |
| 420 | Post-init processing |
| 421 | -------------------- |
| 422 | |
| 423 | The generated :meth:`__init__` code will call a method named |
| 424 | :meth:`__post_init__`, if :meth:`__post_init__` is defined on the |
| 425 | class. It will normally be called as ``self.__post_init__()``. |
| 426 | However, if any ``InitVar`` fields are defined, they will also be |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 427 | passed to :meth:`__post_init__` in the order they were defined in the |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 428 | class. If no :meth:`__init__` method is generated, then |
| 429 | :meth:`__post_init__` will not automatically be called. |
| 430 | |
| 431 | Among other uses, this allows for initializing field values that |
| 432 | depend on one or more other fields. For example:: |
| 433 | |
| 434 | @dataclass |
| 435 | class C: |
| 436 | a: float |
| 437 | b: float |
| 438 | c: float = field(init=False) |
| 439 | |
| 440 | def __post_init__(self): |
| 441 | self.c = self.a + self.b |
| 442 | |
| 443 | See the section below on init-only variables for ways to pass |
| 444 | parameters to :meth:`__post_init__`. Also see the warning about how |
| 445 | :func:`replace` handles ``init=False`` fields. |
| 446 | |
| 447 | Class variables |
| 448 | --------------- |
| 449 | |
| 450 | One of two places where :func:`dataclass` actually inspects the type |
| 451 | of a field is to determine if a field is a class variable as defined |
| 452 | in :pep:`526`. It does this by checking if the type of the field is |
| 453 | ``typing.ClassVar``. If a field is a ``ClassVar``, it is excluded |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 454 | from consideration as a field and is ignored by the dataclass |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 455 | mechanisms. Such ``ClassVar`` pseudo-fields are not returned by the |
| 456 | module-level :func:`fields` function. |
| 457 | |
| 458 | Init-only variables |
| 459 | ------------------- |
| 460 | |
| 461 | The other place where :func:`dataclass` inspects a type annotation is to |
| 462 | determine if a field is an init-only variable. It does this by seeing |
| 463 | if the type of a field is of type ``dataclasses.InitVar``. If a field |
| 464 | is an ``InitVar``, it is considered a pseudo-field called an init-only |
| 465 | field. As it is not a true field, it is not returned by the |
| 466 | module-level :func:`fields` function. Init-only fields are added as |
| 467 | parameters to the generated :meth:`__init__` method, and are passed to |
| 468 | the optional :meth:`__post_init__` method. They are not otherwise used |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 469 | by dataclasses. |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 470 | |
| Daniel Dương | 075b3c3 | 2018-08-24 16:19:24 +0700 | [diff] [blame] | 471 | For example, suppose a field will be initialized from a database, if a |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 472 | value is not provided when creating the class:: |
| 473 | |
| 474 | @dataclass |
| 475 | class C: |
| 476 | i: int |
| 477 | j: int = None |
| 478 | database: InitVar[DatabaseType] = None |
| 479 | |
| 480 | def __post_init__(self, database): |
| 481 | if self.j is None and database is not None: |
| 482 | self.j = database.lookup('j') |
| 483 | |
| 484 | c = C(10, database=my_database) |
| 485 | |
| 486 | In this case, :func:`fields` will return :class:`Field` objects for ``i`` and |
| 487 | ``j``, but not for ``database``. |
| 488 | |
| 489 | Frozen instances |
| 490 | ---------------- |
| 491 | |
| 492 | It is not possible to create truly immutable Python objects. However, |
| 493 | by passing ``frozen=True`` to the :meth:`dataclass` decorator you can |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 494 | emulate immutability. In that case, dataclasses will add |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 495 | :meth:`__setattr__` and :meth:`__delattr__` methods to the class. These |
| 496 | methods will raise a :exc:`FrozenInstanceError` when invoked. |
| 497 | |
| 498 | There is a tiny performance penalty when using ``frozen=True``: |
| 499 | :meth:`__init__` cannot use simple assignment to initialize fields, and |
| 500 | must use :meth:`object.__setattr__`. |
| 501 | |
| 502 | Inheritance |
| 503 | ----------- |
| 504 | |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 505 | When the dataclass is being created by the :meth:`dataclass` decorator, |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 506 | it looks through all of the class's base classes in reverse MRO (that |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 507 | is, starting at :class:`object`) and, for each dataclass that it finds, |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 508 | adds the fields from that base class to an ordered mapping of fields. |
| 509 | After all of the base class fields are added, it adds its own fields |
| 510 | to the ordered mapping. All of the generated methods will use this |
| 511 | combined, calculated ordered mapping of fields. Because the fields |
| 512 | are in insertion order, derived classes override base classes. An |
| 513 | example:: |
| 514 | |
| 515 | @dataclass |
| 516 | class Base: |
| 517 | x: Any = 15.0 |
| 518 | y: int = 0 |
| 519 | |
| 520 | @dataclass |
| 521 | class C(Base): |
| 522 | z: int = 10 |
| 523 | x: int = 15 |
| 524 | |
| 525 | The final list of fields is, in order, ``x``, ``y``, ``z``. The final |
| 526 | type of ``x`` is ``int``, as specified in class ``C``. |
| 527 | |
| 528 | The generated :meth:`__init__` method for ``C`` will look like:: |
| 529 | |
| 530 | def __init__(self, x: int = 15, y: int = 0, z: int = 10): |
| 531 | |
| Eric V. Smith | c028053 | 2021-04-25 20:42:39 -0400 | [diff] [blame] | 532 | Re-ordering of keyword-only parameters in __init__ |
| 533 | -------------------------------------------------- |
| 534 | |
| 535 | After the fields needed for :meth:`__init__` are computed, any |
| 536 | keyword-only fields are put after regular fields. In this example, |
| 537 | ``Base.y`` and ``D.t`` are keyword-only fields:: |
| 538 | |
| 539 | @dataclass |
| 540 | class Base: |
| 541 | x: Any = 15.0 |
| 542 | _: KW_ONLY |
| 543 | y: int = 0 |
| 544 | |
| 545 | @dataclass |
| 546 | class D(Base): |
| 547 | z: int = 10 |
| 548 | t: int = field(kw_only=True, default=0) |
| 549 | |
| 550 | The generated :meth:`__init__` method for ``D`` will look like:: |
| 551 | |
| 552 | def __init__(self, x: Any = 15.0, z: int = 10, *, y: int = 0, t: int = 0): |
| 553 | |
| 554 | The relative ordering of keyword-only arguments is not changed from |
| 555 | the order they are in computed field :meth:`__init__` list. |
| 556 | |
| 557 | |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 558 | Default factory functions |
| 559 | ------------------------- |
| 560 | |
| 561 | If a :func:`field` specifies a ``default_factory``, it is called with |
| 562 | zero arguments when a default value for the field is needed. For |
| 563 | example, to create a new instance of a list, use:: |
| 564 | |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 565 | mylist: list = field(default_factory=list) |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 566 | |
| 567 | If a field is excluded from :meth:`__init__` (using ``init=False``) |
| 568 | and the field also specifies ``default_factory``, then the default |
| 569 | factory function will always be called from the generated |
| 570 | :meth:`__init__` function. This happens because there is no other |
| 571 | way to give the field an initial value. |
| 572 | |
| 573 | Mutable default values |
| 574 | ---------------------- |
| 575 | |
| 576 | Python stores default member variable values in class attributes. |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 577 | Consider this example, not using dataclasses:: |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 578 | |
| 579 | class C: |
| 580 | x = [] |
| 581 | def add(self, element): |
| Tom Faulkner | da5e947 | 2018-07-10 21:39:57 -0500 | [diff] [blame] | 582 | self.x.append(element) |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 583 | |
| 584 | o1 = C() |
| 585 | o2 = C() |
| 586 | o1.add(1) |
| 587 | o2.add(2) |
| 588 | assert o1.x == [1, 2] |
| 589 | assert o1.x is o2.x |
| 590 | |
| 591 | Note that the two instances of class ``C`` share the same class |
| 592 | variable ``x``, as expected. |
| 593 | |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 594 | Using dataclasses, *if* this code was valid:: |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 595 | |
| 596 | @dataclass |
| 597 | class D: |
| 598 | x: List = [] |
| 599 | def add(self, element): |
| 600 | self.x += element |
| 601 | |
| 602 | it would generate code similar to:: |
| 603 | |
| 604 | class D: |
| 605 | x = [] |
| 606 | def __init__(self, x=x): |
| 607 | self.x = x |
| 608 | def add(self, element): |
| 609 | self.x += element |
| 610 | |
| 611 | assert D().x is D().x |
| 612 | |
| 613 | This has the same issue as the original example using class ``C``. |
| 614 | That is, two instances of class ``D`` that do not specify a value for |
| 615 | ``x`` when creating a class instance will share the same copy of |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 616 | ``x``. Because dataclasses just use normal Python class creation |
| 617 | they also share this behavior. There is no general way for Data |
| 618 | Classes to detect this condition. Instead, dataclasses will raise a |
| Eric V. Smith | 98d50cb | 2018-05-16 04:20:43 -0400 | [diff] [blame] | 619 | :exc:`TypeError` if it detects a default parameter of type ``list``, |
| 620 | ``dict``, or ``set``. This is a partial solution, but it does protect |
| 621 | against many common errors. |
| 622 | |
| 623 | Using default factory functions is a way to create new instances of |
| 624 | mutable types as default values for fields:: |
| 625 | |
| 626 | @dataclass |
| 627 | class D: |
| 628 | x: list = field(default_factory=list) |
| 629 | |
| 630 | assert D().x is not D().x |
| Barry Warsaw | 713a936 | 2018-05-16 15:50:07 -0400 | [diff] [blame] | 631 | |
| 632 | Exceptions |
| 633 | ---------- |
| 634 | |
| 635 | .. exception:: FrozenInstanceError |
| 636 | |
| 637 | Raised when an implicitly defined :meth:`__setattr__` or |
| 638 | :meth:`__delattr__` is called on a dataclass which was defined with |
| Llandy Riveron Del Risco | 8a307e4 | 2021-04-26 20:53:28 +0200 | [diff] [blame] | 639 | ``frozen=True``. It is a subclass of :exc:`AttributeError`. |