Skip to content

Commit

Permalink
Fixed #5183 -- Added __deepcopy__, pop() and popitem() to SortedDict.…
Browse files Browse the repository at this point in the history
… Based on

a patch from David Blewett.


git-svn-id: http://code.djangoproject.com/svn/django/trunk@6593 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information
malcolmt committed Oct 22, 2007
1 parent 375a6d7 commit dbd1cb9
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
21 changes: 21 additions & 0 deletions django/utils/datastructures.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -62,6 +62,13 @@ def __init__(self, data=None):
else: else:
self.keyOrder = [key for key, value in data] self.keyOrder = [key for key, value in data]


def __deepcopy__(self,memo):
from copy import deepcopy
obj = self.__class__()
for k, v in self.items():
obj[k] = deepcopy(v, memo)
return obj

def __setitem__(self, key, value): def __setitem__(self, key, value):
dict.__setitem__(self, key, value) dict.__setitem__(self, key, value)
if key not in self.keyOrder: if key not in self.keyOrder:
Expand All @@ -75,6 +82,20 @@ def __iter__(self):
for k in self.keyOrder: for k in self.keyOrder:
yield k yield k


def pop(self, k, *args):
result = dict.pop(self, k, *args)
try:
self.keyOrder.remove(k)
except ValueError:
# Key wasn't in the dictionary in the first place. No problem.
pass
return result

def popitem(self):
result = dict.popitem(self)
self.keyOrder.remove(result[0])
return result

def items(self): def items(self):
return zip(self.keyOrder, self.values()) return zip(self.keyOrder, self.values())


Expand Down
11 changes: 11 additions & 0 deletions tests/regressiontests/datastructures/tests.py
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -54,6 +54,17 @@
True True
>>> print repr(d) >>> print repr(d)
{'one': 'not one', 'two': 'two', 'three': 'three'} {'one': 'not one', 'two': 'two', 'three': 'three'}
>>> d.pop('one', 'missing')
'not one'
>>> d.pop('one', 'missing')
'missing'
We don't know which item will be popped in popitem(), so we'll just check that
the number of keys has decreased.
>>> l = len(d)
>>> _ = d.popitem()
>>> l - len(d)
1
Init from sequence of tuples Init from sequence of tuples
>>> d = SortedDict(( >>> d = SortedDict((
Expand Down

0 comments on commit dbd1cb9

Please sign in to comment.