[Python-ideas] Automatic context managers
David Mertz
mertz at gnosis.cx
Sat Apr 27 01:51:47 CEST 2013
On Apr 26, 2013, at 4:14 PM, Bruce Leban wrote:
> 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(...)
Yeah sure. I was just demonstrating what's possible in a toy way. I actually feel like simply using the 'with' statement is perfectly fine and perfectly clear. But you *can* you could also wrap the bunch of chained methods if you wanted too. I'd have to think about how to define that properly for a few minutes, but if you get to the point where there are various conditional exits to the chain, just use a 'with' block, for gosh sake.
with session(...) as x:
x.query(...)
x.filter(...)
if x.something():
x.order_by(...)
else:
x.order_by(...)
if not x.time_to_leave():
data = x.values()
Or whatever details apply to your own program logic. I don't really know SQLAlchemy, but I guess it must be that most of those chained methods return a mutated object, right? That would be easy enough to check for in the proxy, and I guess whenever it got to something that wasn't a mutated object but rather some "plain" values (a list, scalar, dict, etc), that would be time to leave the context manager. I'll leave that as an exercise :-).
--
>>> THE MERTZ PRINCIPLE <<<
There are two essential virtues in which a sentence might engage:
seduction and alliteration. Ancillary virtues include truthfulness,
effectivity, and artfulness.
More information about the Python-ideas
mailing list