[Python-ideas] Automatic context managers

Bruce Leban bruce at leapyear.org
Sat Apr 27 01:14:41 CEST 2013


On Fri, Apr 26, 2013 at 3:55 PM, David Mertz <mertz at gnosis.cx> wrote:

> > Wouldn't that close the resource before the use function is actually
> called? As I read it, it opens, calls getattr(x, 'use'), closes x, then
> calls x.use().
>
> Nope.  The call is inside the context manager.  Whatever is returned is
> stored in 'y' before the resource is closed, and that value of y is
> returned by the proxy function f.
>

Yup, you're right. Clever. And I read the code a bit too quickly. :-) I
think it's a bit more complicated to write a general wrapper though. For
example, to handle chained calls that SQLAlchemy uses you have to know
which calls should close the object and which ones shouldn't.

    data = SafeSession(...).query(...).filter(...).order_by(...).values(...)

The session should be closed after the call to values() [assuming for the
purpose of this discussion that we actually want to close the session]. If
we do it before, it will fail. If we don't do it then, we no longer have a
handle to the session to close it. So you have to know which calls should
close it and which ones shouldn't.

Caveat: Actually, SQLAlchemy is unsuitable for automatic closing because in
some cases it returns an array of objects which are attached to the session
and you need to keep the session alive as long as you need to access any of
the objects, which an automatic mechanism like this wouldn't be able to
handle But it serves to illustrate the point.

--- Bruce
Latest blog post: Alice's Puzzle Page http://www.vroospeak.com
Learn how hackers think: http://j.mp/gruyere-security
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130426/30fbc183/attachment.html>


More information about the Python-ideas mailing list