Deleting objects

Gerrit Holl gerrit at nl.linux.org
Mon Jan 26 16:12:34 EST 2004


user at domain.invalid wrote:
> If I want to "reset" the object so that I get
> all of my memory back, can I just do:
> 
> 	del db

This may work, if you don't have other references.

> or maybe:
> 
> 	for t in db.tables:
> 		del t
> 	
> and expect that I have cleaned up all of my
> memory?
> 
> After writing this out, I see that the answer
> is clearly yes, but I will post anyway.

The answer is no, really :-)

'del' only removes a certain name from the current namespace. An object
is only destroyed when *all* references to it have been destroyed.
When you are looping over a certain collection, each time the body of
the loop is executed, the loop variable (here 't') gets redefined. So if
the referencecount to a certain object (db.tables[x]) is N, it will
become temporarily N+1 when looping over it: with 'del t', you destroy
the local name, so it becomes N again. Conclusion: This aint gonna work.

Because of this, it is generally better to explicitly kill/destroy/close
something. I don't know anything about databases, but maybe you want to
.close() it? 'del db' may work, but can be tricky if other objects, like
dicts, lists, sets or others, contain (nameless) references to the
object.

yours,
Gerrit.

-- 
This is my signature.
-- 
PrePEP: Builtin path type
    http://people.nl.linux.org/~gerrit/creaties/path/pep-xxxx.html
Asperger's Syndrome - a personal approach:
	http://people.nl.linux.org/~gerrit/english/




More information about the Python-list mailing list