Scope objects

Robert Dailey rcdailey at gmail.com
Fri Jun 5 23:16:31 EDT 2009


On Jun 5, 9:07 pm, Chris Rebert <c... at rebertia.com> wrote:
> On Fri, Jun 5, 2009 at 6: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.
>
> 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

Thanks! This is PERFECT!



More information about the Python-list mailing list