I was using the SortedDict implementation from django/utils/datastructures.py for my own use in a project, and came across a problem when I need to do a deepcopy of a SortedDict object. I consistently got the following error:
Python 2.4:
Python 2.4.4 (#1, Aug 11 2007, 00:45:55)
[GCC 3.4.4 (Gentoo 3.4.4-r1, ssp-3.4.4-1.0, pie-8.7.8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from django.utils.datastructures import SortedDict
>>> from copy import deepcopy
>>> sd = SortedDict({'test': 1})
>>> sd_c = deepcopy(sd)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "/usr/lib/python2.4/copy.py", line 204, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.4/copy.py", line 348, in _reconstruct
y[key] = value
File "django/utils/datastructures.py", line 62, in __setitem__
if key not in self.keyOrder:
AttributeError: 'SortedDict' object has no attribute 'keyOrder'
and 2.5:
Python 2.5.1 (r251:54863, Aug 13 2007, 20:15:26)
[GCC 3.4.4 (Gentoo 3.4.4-r1, ssp-3.4.4-1.0, pie-8.7.8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from django.utils.datastructures import SortedDict
>>> from copy import deepcopy
>>> sd = SortedDict({'test': 1})
>>> sd_c = deepcopy(sd)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.5/copy.py", line 189, in deepcopy
y = _reconstruct(x, rv, 1, memo)
File "/usr/lib/python2.5/copy.py", line 334, in _reconstruct
y[key] = value
File "django/utils/datastructures.py", line 62, in __setitem__
if key not in self.keyOrder:
AttributeError: 'SortedDict' object has no attribute 'keyOrder'
The attached patch implements __deepcopy__ in a way that avoids these errors.