Skip to content

Commit 0c62e09

Browse files
bpo-32216: Update dataclasses documentation (GH-6913) (#6918)
(cherry picked from commit 713a936) Co-authored-by: Barry Warsaw <[email protected]>
1 parent 447fdd1 commit 0c62e09

1 file changed

Lines changed: 79 additions & 75 deletions

File tree

Doc/library/dataclasses.rst

Lines changed: 79 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -117,50 +117,46 @@ Module-level decorators, classes, and functions
117117
:meth:`__le__`, :meth:`__gt__`, or :meth:`__ge__`, then
118118
:exc:`ValueError` is raised.
119119

120-
- ``unsafe_hash``: If ``False`` (the default), the :meth:`__hash__` method
120+
- ``unsafe_hash``: If ``False`` (the default), a :meth:`__hash__` method
121121
is generated according to how ``eq`` and ``frozen`` are set.
122122

123-
If ``eq`` and ``frozen`` are both true, :func:`dataclass` will
124-
generate a :meth:`__hash__` method for you. If ``eq`` is true
125-
and ``frozen`` is false, :meth:`__hash__` will be set to
126-
``None``, marking it unhashable (which it is, since it is
127-
mutable). If ``eq`` is false, :meth:`__hash__` will be left
128-
untouched meaning the :meth:`__hash__` method of the superclass
129-
will be used (if the superclass is :class:`object`, this means it will
130-
fall back to id-based hashing).
131-
132-
Although not recommended, you can force :func:`dataclass` to
133-
create a :meth:`__hash__` method with ``unsafe_hash=True``. This
134-
might be the case if your class is logically immutable but can
135-
nonetheless be mutated. This is a specialized use case and should
136-
be considered carefully.
137-
138-
If a class already has an explicitely defined :meth:`__hash__`
139-
the behavior when adding :meth:`__hash__` is modified. An
140-
expicitely defined :meth:`__hash__` is defined when:
141-
142-
- :meth:`__eq__` is defined in the class and :meth:`__hash__` is defined
143-
with any value other than ``None``.
144-
145-
- :meth:`__eq__` is defined in the class and any non-``None``
146-
:meth:`__hash__` is defined.
147-
148-
- :meth:`__eq__` is not defined on the class, and any :meth:`__hash__` is
149-
defined.
150-
151-
If ``unsafe_hash`` is true and an explicitely defined :meth:`__hash__`
152-
is present, then :exc:`ValueError` is raised.
153-
154-
If ``unsafe_hash`` is false and an explicitely defined :meth:`__hash__`
155-
is present, then no :meth:`__hash__` is added.
156-
157-
See the Python documentation for more information.
123+
:meth:`__hash__` is used by built-in :meth:`hash()`, and when objects are
124+
added to hashed collections such as dictionaries and sets. Having a
125+
:meth:`__hash__` implies that instances of the class are immutable.
126+
Mutability is a complicated property that depends on the programmer's
127+
intent, the existence and behavior of :meth:`__eq__`, and the values of
128+
the ``eq`` and ``frozen`` flags in the :func:`dataclass` decorator.
129+
130+
By default, :func:`dataclass` will not implicitly add a :meth:`__hash__`
131+
method unless it is safe to do so. Neither will it add or change an
132+
existing explicitly defined :meth:`__hash__` method. Setting the class
133+
attribute ``__hash__ = None`` has a specific meaning to Python, as
134+
described in the :meth:`__hash__` documentation.
135+
136+
If :meth:`__hash__` is not explicit defined, or if it is set to ``None``,
137+
then :func:`dataclass` *may* add an implicit :meth:`__hash__` method.
138+
Although not recommended, you can force :func:`dataclass` to create a
139+
:meth:`__hash__` method with ``unsafe_hash=True``. This might be the case
140+
if your class is logically immutable but can nonetheless be mutated.
141+
This is a specialized use case and should be considered carefully.
142+
143+
Here are the rules governing implicit creation of a :meth:`__hash__`
144+
method. Note that you cannot both have an explicit :meth:`__hash__`
145+
method in your dataclass and set ``unsafe_hash=True``; this will result
146+
in a :exc:`TypeError`.
147+
148+
If ``eq`` and ``frozen`` are both true, by default :func:`dataclass` will
149+
generate a :meth:`__hash__` method for you. If ``eq`` is true and
150+
``frozen`` is false, :meth:`__hash__` will be set to ``None``, marking it
151+
unhashable (which it is, since it is mutable). If ``eq`` is false,
152+
:meth:`__hash__` will be left untouched meaning the :meth:`__hash__`
153+
method of the superclass will be used (if the superclass is
154+
:class:`object`, this means it will fall back to id-based hashing).
158155

159156
- ``frozen``: If true (the default is False), assigning to fields will
160-
generate an exception. This emulates read-only frozen instances.
161-
If either :meth:`__getattr__` or :meth:`__setattr__` is defined in
162-
the class, then :exc:`ValueError` is raised. See the discussion
163-
below.
157+
generate an exception. This emulates read-only frozen instances. If
158+
:meth:`__setattr__` or :meth:`__delattr__` is defined in the class, then
159+
:exc:`TypeError` is raised. See the discussion below.
164160

165161
``field``\s may optionally specify a default value, using normal
166162
Python syntax::
@@ -182,17 +178,17 @@ Module-level decorators, classes, and functions
182178
.. function:: field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata=None)
183179

184180
For common and simple use cases, no other functionality is
185-
required. There are, however, some Data Class features that
181+
required. There are, however, some dataclass features that
186182
require additional per-field information. To satisfy this need for
187183
additional information, you can replace the default field value
188184
with a call to the provided :func:`field` function. For example::
189185

190186
@dataclass
191187
class C:
192-
l: List[int] = field(default_factory=list)
188+
mylist: List[int] = field(default_factory=list)
193189

194190
c = C()
195-
c.l += [1, 2, 3]
191+
c.mylist += [1, 2, 3]
196192

197193
As shown above, the ``MISSING`` value is a sentinel object used to
198194
detect if the ``default`` and ``default_factory`` parameters are
@@ -222,7 +218,7 @@ Module-level decorators, classes, and functions
222218
generated equality and comparison methods (:meth:`__eq__`,
223219
:meth:`__gt__`, et al.).
224220

225-
- ``hash``: This can be a bool or ``None``. If True, this field is
221+
- ``hash``: This can be a bool or ``None``. If true, this field is
226222
included in the generated :meth:`__hash__` method. If ``None`` (the
227223
default), use the value of ``compare``: this would normally be
228224
the expected behavior. A field should be considered in the hash
@@ -283,17 +279,16 @@ Module-level decorators, classes, and functions
283279

284280
.. function:: fields(class_or_instance)
285281

286-
Returns a tuple of :class:`Field` objects
287-
that define the fields for this Data Class. Accepts either a Data
288-
Class, or an instance of a Data Class. Raises :exc:`ValueError` if
289-
not passed a Data Class or instance of one. Does not return
290-
pseudo-fields which are ``ClassVar`` or ``InitVar``.
282+
Returns a tuple of :class:`Field` objects that define the fields for this
283+
dataclass. Accepts either a dataclass, or an instance of a dataclass.
284+
Raises :exc:`TypeError` if not passed a dataclass or instance of one.
285+
Does not return pseudo-fields which are ``ClassVar`` or ``InitVar``.
291286

292287
.. function:: asdict(instance, *, dict_factory=dict)
293288

294-
Converts the Data Class ``instance`` to a dict (by using the
295-
factory function ``dict_factory``). Each Data Class is converted
296-
to a dict of its fields, as ``name: value`` pairs. Data Classes, dicts,
289+
Converts the dataclass ``instance`` to a dict (by using the
290+
factory function ``dict_factory``). Each dataclass is converted
291+
to a dict of its fields, as ``name: value`` pairs. dataclasses, dicts,
297292
lists, and tuples are recursed into. For example::
298293

299294
@dataclass
@@ -303,33 +298,33 @@ Module-level decorators, classes, and functions
303298

304299
@dataclass
305300
class C:
306-
l: List[Point]
301+
mylist: List[Point]
307302

308303
p = Point(10, 20)
309304
assert asdict(p) == {'x': 10, 'y': 20}
310305

311306
c = C([Point(0, 0), Point(10, 4)])
312-
assert asdict(c) == {'l': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
307+
assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
313308

314-
Raises :exc:`TypeError` if ``instance`` is not a Data Class instance.
309+
Raises :exc:`TypeError` if ``instance`` is not a dataclass instance.
315310

316311
.. function:: astuple(*, tuple_factory=tuple)
317312

318-
Converts the Data Class ``instance`` to a tuple (by using the
319-
factory function ``tuple_factory``). Each Data Class is converted
320-
to a tuple of its field values. Data Classes, dicts, lists, and
313+
Converts the dataclass ``instance`` to a tuple (by using the
314+
factory function ``tuple_factory``). Each dataclass is converted
315+
to a tuple of its field values. dataclasses, dicts, lists, and
321316
tuples are recursed into.
322317

323318
Continuing from the previous example::
324319

325320
assert astuple(p) == (10, 20)
326321
assert astuple(c) == ([(0, 0), (10, 4)],)
327322

328-
Raises :exc:`TypeError` if ``instance`` is not a Data Class instance.
323+
Raises :exc:`TypeError` if ``instance`` is not a dataclass instance.
329324

330325
.. function:: make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
331326

332-
Creates a new Data Class with name ``cls_name``, fields as defined
327+
Creates a new dataclass with name ``cls_name``, fields as defined
333328
in ``fields``, base classes as given in ``bases``, and initialized
334329
with a namespace as given in ``namespace``. ``fields`` is an
335330
iterable whose elements are each either ``name``, ``(name, type)``,
@@ -341,7 +336,7 @@ Module-level decorators, classes, and functions
341336
This function is not strictly required, because any Python
342337
mechanism for creating a new class with ``__annotations__`` can
343338
then apply the :func:`dataclass` function to convert that class to
344-
a Data Class. This function is provided as a convenience. For
339+
a dataclass. This function is provided as a convenience. For
345340
example::
346341

347342
C = make_dataclass('C',
@@ -369,14 +364,14 @@ Module-level decorators, classes, and functions
369364
specify fields, raises :exc:`TypeError`.
370365

371366
The newly returned object is created by calling the :meth:`__init__`
372-
method of the Data Class. This ensures that
367+
method of the dataclass. This ensures that
373368
:meth:`__post_init__`, if present, is also called.
374369

375370
Init-only variables without default values, if any exist, must be
376371
specified on the call to :func:`replace` so that they can be passed to
377372
:meth:`__init__` and :meth:`__post_init__`.
378373

379-
It is an error for :func:`changes` to contain any fields that are
374+
It is an error for ``changes`` to contain any fields that are
380375
defined as having ``init=False``. A :exc:`ValueError` will be raised
381376
in this case.
382377

@@ -408,7 +403,7 @@ The generated :meth:`__init__` code will call a method named
408403
:meth:`__post_init__`, if :meth:`__post_init__` is defined on the
409404
class. It will normally be called as ``self.__post_init__()``.
410405
However, if any ``InitVar`` fields are defined, they will also be
411-
passed to :meth:`__post_init` in the order they were defined in the
406+
passed to :meth:`__post_init__` in the order they were defined in the
412407
class. If no :meth:`__init__` method is generated, then
413408
:meth:`__post_init__` will not automatically be called.
414409

@@ -435,7 +430,7 @@ One of two places where :func:`dataclass` actually inspects the type
435430
of a field is to determine if a field is a class variable as defined
436431
in :pep:`526`. It does this by checking if the type of the field is
437432
``typing.ClassVar``. If a field is a ``ClassVar``, it is excluded
438-
from consideration as a field and is ignored by the Data Class
433+
from consideration as a field and is ignored by the dataclass
439434
mechanisms. Such ``ClassVar`` pseudo-fields are not returned by the
440435
module-level :func:`fields` function.
441436

@@ -450,7 +445,7 @@ field. As it is not a true field, it is not returned by the
450445
module-level :func:`fields` function. Init-only fields are added as
451446
parameters to the generated :meth:`__init__` method, and are passed to
452447
the optional :meth:`__post_init__` method. They are not otherwise used
453-
by Data Classes.
448+
by dataclasses.
454449

455450
For example, suppose a field will be initialzed from a database, if a
456451
value is not provided when creating the class::
@@ -475,7 +470,7 @@ Frozen instances
475470

476471
It is not possible to create truly immutable Python objects. However,
477472
by passing ``frozen=True`` to the :meth:`dataclass` decorator you can
478-
emulate immutability. In that case, Data Classes will add
473+
emulate immutability. In that case, dataclasses will add
479474
:meth:`__setattr__` and :meth:`__delattr__` methods to the class. These
480475
methods will raise a :exc:`FrozenInstanceError` when invoked.
481476

@@ -486,9 +481,9 @@ must use :meth:`object.__setattr__`.
486481
Inheritance
487482
-----------
488483

489-
When the Data Class is being created by the :meth:`dataclass` decorator,
484+
When the dataclass is being created by the :meth:`dataclass` decorator,
490485
it looks through all of the class's base classes in reverse MRO (that
491-
is, starting at :class:`object`) and, for each Data Class that it finds,
486+
is, starting at :class:`object`) and, for each dataclass that it finds,
492487
adds the fields from that base class to an ordered mapping of fields.
493488
After all of the base class fields are added, it adds its own fields
494489
to the ordered mapping. All of the generated methods will use this
@@ -520,7 +515,7 @@ Default factory functions
520515
zero arguments when a default value for the field is needed. For
521516
example, to create a new instance of a list, use::
522517

523-
l: list = field(default_factory=list)
518+
mylist: list = field(default_factory=list)
524519

525520
If a field is excluded from :meth:`__init__` (using ``init=False``)
526521
and the field also specifies ``default_factory``, then the default
@@ -532,7 +527,7 @@ Mutable default values
532527
----------------------
533528

534529
Python stores default member variable values in class attributes.
535-
Consider this example, not using Data Classes::
530+
Consider this example, not using dataclasses::
536531

537532
class C:
538533
x = []
@@ -549,7 +544,7 @@ Mutable default values
549544
Note that the two instances of class ``C`` share the same class
550545
variable ``x``, as expected.
551546

552-
Using Data Classes, *if* this code was valid::
547+
Using dataclasses, *if* this code was valid::
553548

554549
@dataclass
555550
class D:
@@ -571,9 +566,9 @@ Mutable default values
571566
This has the same issue as the original example using class ``C``.
572567
That is, two instances of class ``D`` that do not specify a value for
573568
``x`` when creating a class instance will share the same copy of
574-
``x``. Because Data Classes just use normal Python class creation
575-
they also share this problem. There is no general way for Data
576-
Classes to detect this condition. Instead, Data Classes will raise a
569+
``x``. Because dataclasses just use normal Python class creation
570+
they also share this behavior. There is no general way for Data
571+
Classes to detect this condition. Instead, dataclasses will raise a
577572
:exc:`TypeError` if it detects a default parameter of type ``list``,
578573
``dict``, or ``set``. This is a partial solution, but it does protect
579574
against many common errors.
@@ -586,3 +581,12 @@ Mutable default values
586581
x: list = field(default_factory=list)
587582

588583
assert D().x is not D().x
584+
585+
Exceptions
586+
----------
587+
588+
.. exception:: FrozenInstanceError
589+
590+
Raised when an implicitly defined :meth:`__setattr__` or
591+
:meth:`__delattr__` is called on a dataclass which was defined with
592+
``frozen=True``.

0 commit comments

Comments
 (0)