Scope objects

Gabriel Genellina gagsl-py2 at
Sat Jun 6 05:44:47 EDT 2009

En Sat, 06 Jun 2009 03:03:34 -0300, <s0suk3 at> escribió:
> On Jun 5, 8:56 pm, Robert Dailey <rcdai... at> wrote:

>> Is it possible to create an object in Python that will clean itself up
>> at function exit? I realize destruction of objects may not occur
>> immediately and can be garbage collected, but this functionality would
>> still be great to have.
> I don't know what you mean by:
> "I realize destruction of objects may not occur immediately and can be
> garbage collected"
> Aren't you just missing ordinary destructors (__del__() methods)?
> These are closest to C++ destructors AFAICS. As far as I know, these
> are guaranteed to be called when an object goes out of scope. (Note
> that destruction and garbage collection are different operations; an
> object may be destructed without being immediately garbage-collected
> afterwards.)

No, that's not how it works in Python (and I think you're mistaken for C++  
See and specially

"Objects are never explicitly destroyed; however, when they become  
unreachable they may be garbage-collected. An implementation is allowed to  
postpone garbage collection or omit it altogether."

CPython uses a "reference count" scheme - an object is destroyed as soon  
as it loses its last reference. Other implementations may choose another  
strategy - in fact, Jython relies on garbage collection instead; object  
destruction may be delayed an arbitrary amount of time. (CPython has a  
garbage collector too, but its purpose is to detect and break object  

So the OP is right - you can't rely on object destruction to perform any  
cleanup; use try/finally or a with statement instead.

>>>> import sys
>>>> class Simple:
> ...     def __init__(self): sys.stdout.write("Simple.__init__()\n")
> ...     def __del__(self):  sys.stdout.write("Simple.__del__()\n")
> ...
>>>> def f():
> ...     s = Simple()
> ...     sys.stdout.write("f()\n")
> ...     # 's' now going out of scope...
> ...
>>>> f()
> Simple.__init__()
> f()
> Simple.__del__()

This behaviour isn't guaranteed and you should not rely on it. Also, try  
again with:

def f():
   s = Simple()
   t = Simple()
   s.x = t
   t.x = s

Gabriel Genellina

More information about the Python-list mailing list