From 67e340e5b5a792c6a098c2c52cd4feb2353b2346 Mon Sep 17 00:00:00 2001 From: machines-6657 Date: Sat, 3 Oct 2026 17:13:15 +0800 Subject: [PATCH] Fix Box.popitem LIFO order --- AUTHORS.rst | 1 + CHANGES.rst | 5 +++++ box/box.py | 2 +- test/test_box.py | 3 ++- 4 files changed, 9 insertions(+), 2 deletions(-) diff --git a/AUTHORS.rst b/AUTHORS.rst index 6b44851..96bfe3b 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -37,6 +37,7 @@ Code contributions: - Jesper Schlegel (jesperschlegel) - J vanBemmel (jbemmel) - m-janicki +- machines-6657 (machines-6657) Suggestions and bug reporting: diff --git a/CHANGES.rst b/CHANGES.rst index c4a347d..3d01514 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,6 +1,11 @@ Changelog ========= +Unreleased +---------- + +* Fix `Box.popitem()` to remove the most recently inserted item, matching `dict.popitem()`. + Version 7.4.1 ------------- diff --git a/box/box.py b/box/box.py index 8252643..1acb685 100644 --- a/box/box.py +++ b/box/box.py @@ -782,7 +782,7 @@ def popitem(self): if self._box_config["frozen_box"]: raise BoxError("Box is frozen") try: - key = next(self.__iter__()) + key = next(self.__reversed__()) except StopIteration: raise BoxKeyError("Empty box") from None return key, self.pop(key) diff --git a/test/test_box.py b/test/test_box.py index e5c56e0..e5ccab3 100644 --- a/test/test_box.py +++ b/test/test_box.py @@ -882,7 +882,8 @@ def test_pop(self): assert bx.pop("c", True) is not True def test_pop_items(self): - bx = Box(a=4) + bx = Box(a=4, b=5) + assert bx.popitem() == ("b", 5) assert bx.popitem() == ("a", 4) with pytest.raises(BoxKeyError): assert bx.popitem()