]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-147957: pop items from UserDict in LIFO order (gh-147958) main
authorAnerdw <yimandrew27@gmail.com>
Wed, 15 Apr 2026 04:29:41 +0000 (23:29 -0500)
committerGitHub <noreply@github.com>
Wed, 15 Apr 2026 04:29:41 +0000 (23:29 -0500)
Doc/library/collections.rst
Lib/collections/__init__.py
Misc/NEWS.d/next/Library/2026-04-01-07-10-49.gh-issue-147957.QXf5Xx.rst [new file with mode: 0644]

index c8dcaef80188cd58e2b102eb9ab06f6900ef6c9e..cb9300f072b9e77149ac956dcc197bb0a4378b2c 100644 (file)
@@ -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
 -------------------------
index febab521629228cbd29a8ea3cc6ed4c649d96bde..20f1e728733fec6662135caeeaa6e1966cad09de 100644 (file)
@@ -1253,6 +1253,20 @@ class UserDict(_collections_abc.MutableMapping):
         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()
diff --git a/Misc/NEWS.d/next/Library/2026-04-01-07-10-49.gh-issue-147957.QXf5Xx.rst b/Misc/NEWS.d/next/Library/2026-04-01-07-10-49.gh-issue-147957.QXf5Xx.rst
new file mode 100644 (file)
index 0000000..4a0e15d
--- /dev/null
@@ -0,0 +1 @@
+Guarantees that :meth:`collections.UserDict.popitem` will pop in the same order as the wrapped dictionary rather than an arbitrary order.