[Python-ideas] Automatic context managers
Random832
random832 at fastmail.us
Sat Apr 27 03:43:29 CEST 2013
On 04/26/2013 03:45 PM, Bruce Leban wrote:
>
> On Fri, Apr 26, 2013 at 12:30 PM, Andrew Svetlov
> <andrew.svetlov at gmail.com <mailto:andrew.svetlov at gmail.com>> wrote:
>
> On Fri, Apr 26, 2013 at 9:54 PM, <random832 at fastmail.us
> <mailto: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.
If someone wanted to do that, lambda's already here.
(lambda a, b, c: (-b + sqrt(b*b - 4 * a * c)) / (2 * a))(3,4,5)
The original syntax I was going to suggest would have been something
more along the lines of (with open(resource) as x: x.use()), but figured
the syntax I ended up posting would be more pythonic (by analogy to list
comprehensions or if-else)
The purpose of this would be to call cleanup code. Anything can be misused.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130426/6fa6d65a/attachment.html>
More information about the Python-ideas
mailing list