Skip to content
Open
7 changes: 7 additions & 0 deletions Doc/library/collections.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1346,7 +1346,14 @@ attribute.
A real dictionary used to store the contents of the :class:`UserDict`
class.

:class:`!UserDict` instances also override the following method:

.. method:: popitem

Remove and return a ``(key, value)`` pair from the wrapped dictionary. Pairs are
returned in the same order as ``data.popitem()``. (For the default
:meth:`dict.popitem`, this order is :abbr:`LIFO (last-in, first-out)`.) If the
dictionary is empty, raises a :exc:`KeyError`.

:class:`UserList` objects
-------------------------
Expand Down
14 changes: 14 additions & 0 deletions Lib/collections/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1253,6 +1253,20 @@ def copy(self):
c.update(self)
return c


# This method has a default implementation in MutableMapping, but dict's
# equivalent is last-in, first-out instead of first-in, first-out.
def popitem(self):
"""Remove and return a (key, value) pair as a 2-tuple.

Removes pairs in the same order as the wrapped mapping's popitem()
method. For dict objects (the default), that order is last-in,
first-out (LIFO).
Raises KeyError if the UserDict is empty.
"""
return self.data.popitem()


@classmethod
def fromkeys(cls, iterable, value=None):
d = cls()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Guarantees that :meth:`collections.UserDict.popitem` will pop in the same order as the wrapped dictionary rather than an arbitrary order.
Loading