We are checking whether one of our packages leaves garbage objects in the Python gc and found that collections.OrderedDict
objects are not deleted by the ref-count mechanism but are put into the GC, with the following references (when pprint'ing them and tweaking the output a little):
<type 'list'> object at 0x10a876ab8:
[ <Recursive reference to list object at 0x10a876ab8>,
<Recursive reference to list object at 0x10a876ab8>,
None]
This seems to be the same issue as the one reported in https://bugs.python.org/issue9825. That issue was fixed in Python 3.2, and indeed, the reference cycle shown above appears on Python 2.7 but not on Python 3.7.
Is there a ref-cycle free alternative to collections.OrderedDict
for Python 2.7?
Update:
I found that
ordereddict.OrderedDict
also has the same reference cycle.I am fully aware that Python 2.7 is out of support. Nevertheless, we still need to support our package on Python 2.7.
The answer of @Ramsha Siddiqui points to the SortedDict of Django. I verified that in Django 1.7, its SortedDict does not have reference cycles. However, SortedDict was removed from Django (at least in its version 1.11).