[Python-ideas] Automatic context managers

Bruce Leban bruce at leapyear.org
Fri Apr 26 21:45:45 CEST 2013


On Fri, Apr 26, 2013 at 12:30 PM, Andrew Svetlov
<andrew.svetlov at gmail.com>wrote:

> On Fri, Apr 26, 2013 at 9:54 PM,  <random832 at fastmail.us> wrote:
> > What about a with expression?
> >
> > boolean = x.use() with x as open(resource)
>
> interesting idea. I see nothing bad with proposed construction.
> Any objections? I've miss something?
>

The most obvious thing as that 'as' is backwards from the with statement.
Also this requires you to come up with a name which you have to repeat while

with(open(resource)).use()


doesn't. On the other hand, it allows you to do:

result = [x.foo(), x.bar()] with open(resource) as x

which opens the way to freewheeling inline assignment:

@contextmanager
def assign(x):
    yield x

result = (-b + sqrt(b*b - 4 * a * c)) / (2 * a) with assign(3) as a with
assign(4) as b with assign(5) as c


I don't think that's a good thing.

--- 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/fed20607/attachment.html>


More information about the Python-ideas mailing list