bpo-32506: Change dataclasses from OrderedDict to plain dict. (gh-5131) · python/cpython@d138892 (original) (raw)

1

1

`import sys

`

2

2

`import types

`

3

3

`from copy import deepcopy

`

4

``

`-

import collections

`

5

4

`import inspect

`

6

5

``

7

6

`all = ['dataclass',

`

`@@ -448,11 +447,11 @@ def _set_attribute(cls, name, value):

`

448

447

``

449

448

``

450

449

`def _process_class(cls, repr, eq, order, hash, init, frozen):

`

451

``

`-

Use an OrderedDict because:

`

452

``

`-

- Order matters!

`

453

``

`-

- Derived class fields overwrite base class fields, but the

`

454

``

`-

order is defined by the base class, which is found first.

`

455

``

`-

fields = collections.OrderedDict()

`

``

450

`+

Now that dicts retain insertion order, there's no reason to use

`

``

451

`+

an ordered dict. I am leveraging that ordering here, because

`

``

452

`+

derived class fields overwrite base class fields, but the order

`

``

453

`+

is defined by the base class, which is found first.

`

``

454

`+

fields = {}

`

456

455

``

457

456

`# Find our base classes in reverse MRO order, and exclude

`

458

457

`# ourselves. In reversed order so that more derived classes

`

`@@ -612,7 +611,8 @@ def fields(class_or_instance):

`

612

611

`except AttributeError:

`

613

612

`raise TypeError('must be called with a dataclass type or instance')

`

614

613

``

615

``

`-

Exclude pseudo-fields.

`

``

614

`+

Exclude pseudo-fields. Note that fields is sorted by insertion

`

``

615

`+

order, so the order of the tuple is as the fields were defined.

`

616

616

`return tuple(f for f in fields.values() if f._field_type is _FIELD)

`

617

617

``

618

618

``

`@@ -735,7 +735,7 @@ class C(Base):

`

735

735

`# Copy namespace since we're going to mutate it.

`

736

736

`namespace = namespace.copy()

`

737

737

``

738

``

`-

anns = collections.OrderedDict()

`

``

738

`+

anns = {}

`

739

739

`for item in fields:

`

740

740

`if isinstance(item, str):

`

741

741

`name = item

`