bpo-32216: Update dataclasses documentation (#6913) · python/cpython@713a936 (original) (raw)

`@@ -117,50 +117,46 @@ Module-level decorators, classes, and functions

`

117

117

`` :meth:__le__, :meth:__gt__, or :meth:__ge__, then

``

118

118

`` :exc:ValueError is raised.

``

119

119

``

120

``


 - ``unsafe_hash``: If ``False`` (the default), the :meth:`__hash__` method

``

120


 - ``unsafe_hash``: If ``False`` (the default), a :meth:`__hash__` method

121

121

``` is generated according to how eq and frozen are set.


`122`

`122`

``

`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

``

`` -

``

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

``

`` -

``

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).

``

158

155

``

159

156

``` - 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.

``

`164`

`160`

``

`165`

`161`

```  ``field``\s may optionally specify a default value, using normal

166

162

` Python syntax::

`

`@@ -182,17 +178,17 @@ Module-level decorators, classes, and functions

`

182

178

`.. function:: field(*, default=MISSING, default_factory=MISSING, repr=True, hash=None, init=True, compare=True, metadata=None)

`

183

179

``

184

180

` 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

`

186

182

` require additional per-field information. To satisfy this need for

`

187

183

` additional information, you can replace the default field value

`

188

184

`` with a call to the provided :func:field function. For example::

``

189

185

``

190

186

` @dataclass

`

191

187

` class C:

`

192

``

`-

l: List[int] = field(default_factory=list)

`

``

188

`+

mylist: List[int] = field(default_factory=list)

`

193

189

``

194

190

` c = C()

`

195

``

`-

c.l += [1, 2, 3]

`

``

191

`+

c.mylist += [1, 2, 3]

`

196

192

``

197

193

``` As shown above, the MISSING value is a sentinel object used to


`198`

`194`

```  detect if the ``default`` and ``default_factory`` parameters are

`@@ -222,7 +218,7 @@ Module-level decorators, classes, and functions

`

222

218

`` generated equality and comparison methods (:meth:__eq__,

``

223

219

`` :meth:__gt__, et al.).

``

224

220

``

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

226

222

``` included in the generated :meth:__hash__ method. If None (the


`227`

`223`

```  default), use the value of ``compare``: this would normally be

228

224

` the expected behavior. A field should be considered in the hash

`

`@@ -283,17 +279,16 @@ Module-level decorators, classes, and functions

`

283

279

``

284

280

`.. function:: fields(class_or_instance)

`

285

281

``

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``.

291

286

``

292

287

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

`

293

288

``

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,

297

292

` lists, and tuples are recursed into. For example::

`

298

293

``

299

294

` @dataclass

`

`@@ -303,33 +298,33 @@ Module-level decorators, classes, and functions

`

303

298

``

304

299

` @dataclass

`

305

300

` class C:

`

306

``

`-

l: List[Point]

`

``

301

`+

mylist: List[Point]

`

307

302

``

308

303

` p = Point(10, 20)

`

309

304

` assert asdict(p) == {'x': 10, 'y': 20}

`

310

305

``

311

306

` 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}]}

`

313

308

``

314

``


 Raises :exc:`TypeError` if ``instance`` is not a Data Class instance.

``

309


 Raises :exc:`TypeError` if ``instance`` is not a dataclass instance.

315

310

``

316

311

`.. function:: astuple(*, tuple_factory=tuple)

`

317

312

``

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

`

321

316

` tuples are recursed into.

`

322

317

``

323

318

` Continuing from the previous example::

`

324

319

``

325

320

` assert astuple(p) == (10, 20)

`

326

321

` assert astuple(c) == ([(0, 0), (10, 4)],)

`

327

322

``

328

``


 Raises :exc:`TypeError` if ``instance`` is not a Data Class instance.

``

323


 Raises :exc:`TypeError` if ``instance`` is not a dataclass instance.

329

324

``

330

325

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

`

331

326

``

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

333

328

``` in fields, base classes as given in bases, and initialized


`334`

`329`

```  with a namespace as given in ``namespace``. ``fields`` is an

335

330

``` iterable whose elements are each either name, (name, type),


`@@ -341,7 +336,7 @@ Module-level decorators, classes, and functions

`

`341`

`336`

` This function is not strictly required, because any Python

`

`342`

`337`

```  mechanism for creating a new class with ``__annotations__`` can

343

338

`` 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

`

345

340

` example::

`

346

341

``

347

342

` C = make_dataclass('C',

`

`@@ -369,14 +364,14 @@ Module-level decorators, classes, and functions

`

369

364

`` specify fields, raises :exc:TypeError.

``

370

365

``

371

366

`` 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

`

373

368

`` :meth:__post_init__, if present, is also called.

``

374

369

``

375

370

` Init-only variables without default values, if any exist, must be

`

376

371

`` specified on the call to :func:replace so that they can be passed to

``

377

372

`` :meth:__init__ and :meth:__post_init__.

``

378

373

``

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

380

375

``` defined as having init=False. A :exc:ValueError will be raised


`381`

`376`

` in this case.

`

`382`

`377`

``

`` @@ -408,7 +403,7 @@ The generated :meth:`__init__` code will call a method named

``

`408`

`403`

`` :meth:`__post_init__`, if :meth:`__post_init__` is defined on the

``

`409`

`404`

``` class. It will normally be called as ``self.__post_init__()``.

410

405

``` 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

``

`412`

`407`

`` class. If no :meth:`__init__` method is generated, then

``

`413`

`408`

`` :meth:`__post_init__` will not automatically be called.

``

`414`

`409`

``

`` @@ -435,7 +430,7 @@ One of two places where :func:`dataclass` actually inspects the type

``

`435`

`430`

`of a field is to determine if a field is a class variable as defined

`

`436`

`431`

`` in :pep:`526`. It does this by checking if the type of the field is

``

`437`

`432`

``` ``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

`

439

434

``` mechanisms. Such ClassVar pseudo-fields are not returned by the


`440`

`435`

`` module-level :func:`fields` function.

``

`441`

`436`

``

`@@ -450,7 +445,7 @@ field. As it is not a true field, it is not returned by the

`

`450`

`445`

`` module-level :func:`fields` function. Init-only fields are added as

``

`451`

`446`

`` parameters to the generated :meth:`__init__` method, and are passed to

``

`452`

`447`

`` the optional :meth:`__post_init__` method. They are not otherwise used

``

`453`

``

`-

by Data Classes.

`

``

`448`

`+

by dataclasses.

`

`454`

`449`

``

`455`

`450`

`For example, suppose a field will be initialzed from a database, if a

`

`456`

`451`

`value is not provided when creating the class::

`

`@@ -475,7 +470,7 @@ Frozen instances

`

`475`

`470`

``

`476`

`471`

`It is not possible to create truly immutable Python objects. However,

`

`477`

`472`

``` 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

`

479

474

`` :meth:__setattr__ and :meth:__delattr__ methods to the class. These

``

480

475

`` methods will raise a :exc:FrozenInstanceError when invoked.

``

481

476

``

`` @@ -486,9 +481,9 @@ must use :meth:object.__setattr__.

``

486

481

`Inheritance

`

487

482

`-----------

`

488

483

``

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,

``

490

485

`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,

``

492

487

`adds the fields from that base class to an ordered mapping of fields.

`

493

488

`After all of the base class fields are added, it adds its own fields

`

494

489

`to the ordered mapping. All of the generated methods will use this

`

`@@ -520,7 +515,7 @@ Default factory functions

`

520

515

` zero arguments when a default value for the field is needed. For

`

521

516

` example, to create a new instance of a list, use::

`

522

517

``

523

``

`-

l: list = field(default_factory=list)

`

``

518

`+

mylist: list = field(default_factory=list)

`

524

519

``

525

520

``` If a field is excluded from :meth:__init__ (using init=False)


`526`

`521`

```  and the field also specifies ``default_factory``, then the default

`@@ -532,7 +527,7 @@ Mutable default values

`

532

527

`----------------------

`

533

528

``

534

529

` Python stores default member variable values in class attributes.

`

535

``

`-

Consider this example, not using Data Classes::

`

``

530

`+

Consider this example, not using dataclasses::

`

536

531

``

537

532

` class C:

`

538

533

` x = []

`

`@@ -549,7 +544,7 @@ Mutable default values

`

549

544

``` Note that the two instances of class C share the same class


`550`

`545`

```  variable ``x``, as expected.

551

546

``

552

``

`-

Using Data Classes, if this code was valid::

`

``

547

`+

Using dataclasses, if this code was valid::

`

553

548

``

554

549

` @dataclass

`

555

550

` class D:

`

`@@ -571,9 +566,9 @@ Mutable default values

`

571

566

``` This has the same issue as the original example using class C.


`572`

`567`

```  That is, two instances of class ``D`` that do not specify a value for

573

568

``` 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

`

577

572

``` :exc:TypeError if it detects a default parameter of type list,


`578`

`573`

```  ``dict``, or ``set``. This is a partial solution, but it does protect

579

574

` against many common errors.

`

`@@ -586,3 +581,12 @@ Mutable default values

`

586

581

` x: list = field(default_factory=list)

`

587

582

``

588

583

` 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``.