Tracking down memory leaks?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Feb 12 10:24:40 EST 2006


On Sun, 12 Feb 2006 06:01:55 -0800, dmsbox2000-list1 at yahoo.com wrote:

> I *think* Python uses reference counting for garbage collection.

Yes it does, with special code for detecting and collecting circular
references.

> I've
> heard talk of people wanting to change this (to mark and sweep?).

Reference counting is too simple to be cool *wink*

[snip]
> Make sure you are not creating
> a circular reference.  Something like this:
> 
> a = [1, 2, 3, 4, 5, 6]
> b = ['a', 'b', 'c', 'd']
> c = [10, 20, 30, 40]
> 
> a[3] = b
> b[1] = c
> c[0] = a
> 
> the last assignment creates a circular refence, and until it is removed,
> non of these objects will be removed from memory.

I believe Python now handles this sort of situation very well now.


> 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



-- 
Steven.




More information about the Python-list mailing list