Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Fixed SortedDict.__copy__()

Fixed #18175 -- Calling SortedDict.__copy__() resulted in changes to
the original dictionary. The reason was likely related to subclassing
dict.

Thanks to linovia for report and patch.
  • Loading branch information...
commit 4b11762f7d7aed2f4f36c4158326c0a4332038f9 1 parent aa1aa1a
Anssi Kääriäinen authored April 30, 2012
10  django/utils/datastructures.py
@@ -128,6 +128,12 @@ def __deepcopy__(self, memo):
128 128
         return self.__class__([(key, copy.deepcopy(value, memo))
129 129
                                for key, value in self.iteritems()])
130 130
 
  131
+    def __copy__(self):
  132
+        # The Python's default copy implementation will alter the state
  133
+        # of self. The reason for this seems complex but is likely related to
  134
+        # subclassing dict.
  135
+        return self.copy()
  136
+
131 137
     def __setitem__(self, key, value):
132 138
         if key not in self:
133 139
             self.keyOrder.append(key)
@@ -200,9 +206,7 @@ def insert(self, index, key, value):
200 206
     def copy(self):
201 207
         """Returns a copy of this object."""
202 208
         # This way of initializing the copy means it works for subclasses, too.
203  
-        obj = self.__class__(self)
204  
-        obj.keyOrder = self.keyOrder[:]
205  
-        return obj
  209
+        return self.__class__(self)
206 210
 
207 211
     def __repr__(self):
208 212
         """
6  tests/regressiontests/utils/datastructures.py
@@ -111,6 +111,12 @@ def test_pickle(self):
111 111
             {7: 'seven', 1: 'one', 9: 'nine'}
112 112
         )
113 113
 
  114
+    def test_copy(self):
  115
+        orig = SortedDict(((1, "one"), (0, "zero"), (2, "two")))
  116
+        copied = copy.copy(orig)
  117
+        self.assertEqual(orig.keys(), [1, 0, 2])
  118
+        self.assertEqual(copied.keys(), [1, 0, 2])
  119
+
114 120
     def test_clear(self):
115 121
         self.d1.clear()
116 122
         self.assertEqual(self.d1, {})

0 notes on commit 4b11762

Please sign in to comment.
Something went wrong with that request. Please try again.