Skip to content

Commit d14e31e

Browse files
authored
gh-147957: pop items from UserDict in LIFO order (gh-147958)
1 parent d0e7c6a commit d14e31e

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

Doc/library/collections.rst

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1346,7 +1346,14 @@ attribute.
13461346
A real dictionary used to store the contents of the :class:`UserDict`
13471347
class.
13481348

1349+
:class:`!UserDict` instances also override the following method:
13491350

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

13511358
:class:`UserList` objects
13521359
-------------------------

Lib/collections/__init__.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1253,6 +1253,20 @@ def copy(self):
12531253
c.update(self)
12541254
return c
12551255

1256+
1257+
# This method has a default implementation in MutableMapping, but dict's
1258+
# equivalent is last-in, first-out instead of first-in, first-out.
1259+
def popitem(self):
1260+
"""Remove and return a (key, value) pair as a 2-tuple.
1261+
1262+
Removes pairs in the same order as the wrapped mapping's popitem()
1263+
method. For dict objects (the default), that order is last-in,
1264+
first-out (LIFO).
1265+
Raises KeyError if the UserDict is empty.
1266+
"""
1267+
return self.data.popitem()
1268+
1269+
12561270
@classmethod
12571271
def fromkeys(cls, iterable, value=None):
12581272
d = cls()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Guarantees that :meth:`collections.UserDict.popitem` will pop in the same order as the wrapped dictionary rather than an arbitrary order.

0 commit comments

Comments
 (0)