Skip to content

Commit

Permalink
bpo-35864: Replace OrderedDict with regular dict in namedtuple() (pyt…
Browse files Browse the repository at this point in the history
…hon#11708)

* Change from OrderedDict to a regular dict

* Add blurb
  • Loading branch information
rhettinger committed Jan 31, 2019
1 parent 0897e0c commit 0bb4bdf
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 2 deletions.
9 changes: 8 additions & 1 deletion Doc/library/collections.rst
Original file line number Diff line number Diff line change
Expand Up @@ -894,11 +894,18 @@ field names, the method and attribute names start with an underscore.

>>> p = Point(x=11, y=22)
>>> p._asdict()
OrderedDict([('x', 11), ('y', 22)])
{'x': 11, 'y': 22}

.. versionchanged:: 3.1
Returns an :class:`OrderedDict` instead of a regular :class:`dict`.

.. versionchanged:: 3.8
Returns a regular :class:`dict` instead of an :class:`OrderedDict`.
As of Python 3.7, regular dicts are guaranteed to be ordered. If the
extra features of :class:`OrderedDict` are required, the suggested
remediation is to cast the result to the desired type:
``OrderedDict(nt._asdict())``.

.. method:: somenamedtuple._replace(**kwargs)

Return a new instance of the named tuple replacing specified fields with new
Expand Down
8 changes: 8 additions & 0 deletions Doc/whatsnew/3.8.rst
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,14 @@ New Modules
Improved Modules
================

* The :meth:`_asdict()` method for :func:`collections.namedtuple` now returns
a :class:`dict` instead of a :class:`collections.OrderedDict`. This works because
regular dicts have guaranteed ordering in since Python 3.7. If the extra
features of :class:`OrderedDict` are required, the suggested remediation is
to cast the result to the desired type: ``OrderedDict(nt._asdict())``.
(Contributed by Raymond Hettinger in :issue:`35864`.)


asyncio
-------

Expand Down
4 changes: 3 additions & 1 deletion Lib/collections/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,9 +426,11 @@ def __repr__(self):
'Return a nicely formatted representation string'
return self.__class__.__name__ + repr_fmt % self

_dict, _zip = dict, zip

def _asdict(self):
'Return a new OrderedDict which maps field names to their values.'
return OrderedDict(zip(self._fields, self))
return _dict(_zip(self._fields, self))

def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
The _asdict() method for collections.namedtuple now returns a regular dict
instead of an OrderedDict.

0 comments on commit 0bb4bdf

Please sign in to comment.