* Add clearer comment to initialization code.

* Add optional argument to popitem() -- modeled
  after Anthon van der Neut's C version.
* Fix method markup in docs.
This commit is contained in:
Raymond Hettinger 2009-03-19 19:59:58 +00:00
parent a0b8d9ad2d
commit 2412299be9
3 changed files with 20 additions and 5 deletions

View File

@ -858,8 +858,11 @@ the items are returned in the order their keys were first added.
.. versionadded:: 2.7
The :meth:`popitem` method for ordered dictionaries returns and removes the
last added entry. The key/value pairs are returned in LIFO order.
.. method:: OrderedDict.popitem(last=True)
The :meth:`popitem` method for ordered dictionaries returns and removes
a (key, value) pair. The pairs are returned in LIFO order if *last* is
true or FIFO order if false.
Equality tests between :class:`OrderedDict` objects are order-sensitive
and are implemented as ``list(od1.items())==list(od2.items())``.
@ -867,3 +870,8 @@ Equality tests between :class:`OrderedDict` objects and other
:class:`Mapping` objects are order-insensitive like regular dictionaries.
This allows :class:`OrderedDict` objects to be substituted anywhere a
regular dictionary is used.
.. seealso::
`Equivalent OrderedDict recipe <http://code.activestate.com/recipes/576693/>`_
that runs on Python 2.4 or later.

View File

@ -30,7 +30,7 @@ class OrderedDict(dict, MutableMapping):
def clear(self):
self.__end = end = []
end += [None, end, end] # null entry
end += [None, end, end] # sentinel node for doubly linked list
self.__map = {} # key --> [key, prev, next]
dict.clear(self)
@ -61,10 +61,10 @@ class OrderedDict(dict, MutableMapping):
yield curr[0]
curr = curr[1]
def popitem(self):
def popitem(self, last=True):
if not self:
raise KeyError('dictionary is empty')
key = next(reversed(self))
key = next(reversed(self)) if last else next(iter(self))
value = self.pop(key)
return key, value

View File

@ -768,12 +768,19 @@ class TestOrderedDict(unittest.TestCase):
class GeneralMappingTests(mapping_tests.BasicTestMappingProtocol):
type2test = OrderedDict
def test_popitem(self):
d = self._empty_mapping()
self.assertRaises(KeyError, d.popitem)
class MyOrderedDict(OrderedDict):
pass
class SubclassMappingTests(mapping_tests.BasicTestMappingProtocol):
type2test = MyOrderedDict
def test_popitem(self):
d = self._empty_mapping()
self.assertRaises(KeyError, d.popitem)
import doctest, collections