File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ :meth:`multidict.MultiDict.popitem` is changed to remove
2+ the latest entry instead of the first.
3+
4+ It gives O(1) amortized complexity.
5+
6+ The standard :meth:`dict.popitem` removes the last entry also.
Original file line number Diff line number Diff line change @@ -456,7 +456,7 @@ def popall(
456456 def popitem (self ) -> tuple [str , _V ]:
457457 """Remove and return an arbitrary (key, value) pair."""
458458 if self ._impl ._items :
459- i = self ._impl ._items .pop (0 )
459+ i = self ._impl ._items .pop ()
460460 self ._impl .incr_version ()
461461 return i [1 ], i [2 ]
462462 else :
Original file line number Diff line number Diff line change @@ -772,13 +772,14 @@ pair_list_pop_item(pair_list_t *list)
772772 return NULL ;
773773 }
774774
775- pair_t * pair = list -> pairs ;
775+ Py_ssize_t pos = list -> size - 1 ;
776+ pair_t * pair = list -> pairs + pos ;
776777 PyObject * ret = PyTuple_Pack (2 , pair -> key , pair -> value );
777778 if (ret == NULL ) {
778779 return NULL ;
779780 }
780781
781- if (pair_list_del_at (list , 0 ) < 0 ) {
782+ if (pair_list_del_at (list , pos ) < 0 ) {
782783 Py_DECREF (ret );
783784 return NULL ;
784785 }
Original file line number Diff line number Diff line change @@ -158,8 +158,8 @@ def test_popitem(
158158 d .add ("key" , "val1" )
159159 d .add ("key" , "val2" )
160160
161- assert ("key" , "val1 " ) == d .popitem ()
162- assert [("key" , "val2 " )] == list (d .items ())
161+ assert ("key" , "val2 " ) == d .popitem ()
162+ assert [("key" , "val1 " )] == list (d .items ())
163163
164164 def test_popitem_empty_multidict (
165165 self ,
@@ -546,9 +546,9 @@ def test_popitem(
546546 d .add ("key" , "val2" )
547547
548548 pair = d .popitem ()
549- assert ("KEY " , "val1 " ) == pair
549+ assert ("key " , "val2 " ) == pair
550550 assert isinstance (pair [0 ], str )
551- assert [("key " , "val2 " )] == list (d .items ())
551+ assert [("KEY " , "val1 " )] == list (d .items ())
552552
553553 def test_popitem_empty_multidict (
554554 self ,
You can’t perform that action at this time.
0 commit comments