__del__ not working with cyclic reference? (and memory-leaked?)

Erik Max Francis max at alcyone.com
Wed Jul 2 01:56:08 EDT 2003


Jane Austine wrote:

> I read the gc module reference thoroughly and
> thanks to your short comment, I could understand it.
> (I should not use __del__ for singleton patterns, but
> any other alternatives?)

I'm not sure why you'd want to use __del__ for a singleton pattern in
the first place, since singleton patterns are supposed to cushion the
creation and destruction of the singleton object away from the interface
user.  What are you trying to do with singleton patterns as it relates
to __del__?

> But does the fact that __del__ is not called for some
> objects mean they are not freed from memory and therefore
> memory-leaked?

No, most operating systems guarantee that when a process exits any
memory it allocated through normal means will be freed whether or not
the application explicitly does it.  So just as with C, C++, or Java,
Python ensures that when the program exits you won't have leaked memory
away from your operating system.

However, Python doesn't make any guarantees about how timely __del__
will be called, or indeed even if it will be (in the case of circular
references).  If you're finding yourself needing to rely on using
__del__ to get rid of important objects (such as those that are attached
to significant resources), a far better solution would be to use try:
... finally: clauses surrounding the usage of such objects:

	resource = Resource()
	try:
	    ... use resource ...
	finally:
	    resource.close()

-- 
   Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
 __ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/  \ Men and women, women and men.  It will never work.
\__/  Erica Jong




More information about the Python-list mailing list