Scope objects

s0suk3 at gmail.com s0suk3 at gmail.com
Sat Jun 6 08:03:34 CEST 2009


On Jun 5, 8:56 pm, Robert Dailey <rcdai... at gmail.com> 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. Consider the following function:
>
> def do_stuff():
>     foo = scope_object()
>     # Do stuff...
>     foo.Cleanup()
>
> It would be nice to avoid the explicit "Cleanup()" call above, and
> have 'foo' just act as if it has a C++ destructor and evoke some
> method at the exit point of a function.

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.)

>>> 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__()
>>>

Sebastian




More information about the Python-list mailing list