Scope objects

Stephen Hansen apt.shansen at
Fri Jun 5 22:07:03 EDT 2009

On Fri, Jun 5, 2009 at 6:56 PM, Robert Dailey <rcdailey 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. 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.

Generally, in CPython at least, 'foo' -would- be destroyed immediately with
the Reference Counting semantics, and thus you could just do whatever
cleanup you needed to in __del__. This isn't the case for other Python
implementations. Its sorta best to not rely on reference counting, but..
sometimes its nice.

Otherwise your only option is the "with statement" in 2.5 (using "from
__future__ import with_statement") or 2.6. In that, you would do:

def do_stuff():
    with scope_object():

The object returned by scope_object() would have its __enter__() and
__exit__() methods called right away. That's the official way to do
'cleaning up code' really these days.

If you need to access the scope object, you'd do "with scope_object() as

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list