Scope objects

Chris Rebert clp2 at rebertia.com
Fri Jun 5 22:07:58 EDT 2009


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

This is exactly what the new `with` statement lets you do. You just
need to define an appropriate context manager. With one, you can code
that as:

def do_stuff():
    with scope_object() as foo:
        #do stuff

More info:  http://www.python.org/dev/peps/pep-0343/

Cheers,
Chris
-- 
http://blog.rebertia.com



More information about the Python-list mailing list