Tracking down memory leaks?
Jean-Paul Calderone
exarkun at divmod.com
Sun Feb 12 13:49:44 EST 2006
On 12 Feb 2006 10:13:02 -0800, "dmsbox2000-list1 at yahoo.com" <dstark7 at gmail.com> wrote:
>>> I'm not an expert on python internals, and it is possible that they have
>>> a way of checking for cases like this. I think the deepcopy method
>>> catches this, but I don't *think* basic garbage collection look for this
>>> sort of thing.
>>
>> deepcopy has nothing to do with garbage collection.
>>
>> This is where you use deepcopy:
>>
>> py> a = [2, 4, [0, 1, 2], 8] # note the nested list
>> py> b = a # b and a both are bound to the same list
>> py> b is a # b is the same list as a, not just a copy
>> True
>> py> c = a[:] # make a shallow copy of a
>> py> c is a # c is a copy of a, not a itself
>> False
>> py> c[2] is a[2] # but both a and c include the same nested list
>> True
>>
>> What if you want c to include a copy of the nested list? That's where you
>> use deepcopy:
>>
>> py> d = copy.deepcopy(a)
>> py> d[2] is a[2]
>> False
>
>What I ment is that deepcopy is recursive, and if you have a circular
>reference in your data structure a recursive copy will become infinite.
> I think deepcopy has the ability to detect this situation. So if it
>could be detected for deepcopy, I don't see why it could not be
>detected for garbage collection purposes.
It's moot, since the garbage collector can collect cycles:
Make a cycle:
>>> a = []
>>> b = []
>>> a.append(b)
>>> b.append(a)
Get rid of all references to all objects participating in it:
>>> del a, b
Explicitly invoke the garbage collector in order to observe the number of objects it cleans up:
>>> gc.collect()
2
Jean-Paul
More information about the Python-list
mailing list