On Sat, Feb 8, 2020 at 1:22 PM Chris Angelico <rosuav@gmail.com> wrote:
On Sun, Feb 9, 2020 at 8:04 AM Random832 <random832@fastmail.com> wrote:
>
> On Fri, Feb 7, 2020, at 13:03, Todd wrote:

> What if you could write pickle.dump(myobj, with open('myfile.p', 'wb'))?
>
> Or other similar examples such as (with open('myfile')).read() - have the compiler automatically transform the code into equivalent to wrapping the statement in a with block.
>

Exactly how much code would be wrapped in the 'with' block?

This is an intriguing idea, and in the example it's fairly easy to wrap the entire statement in the with block. It gets a bit more complicated with short-circuit logic. This is a contrived example to make it easier to read:

result = (with alpha()) and ((with beta()) if (with gamma()) else (with delta()))

needs to be interpreted something like:

with _alpha := alpha():
    if _alpha:
        with _gamma:= gamma():
            if _gamma:
                with _beta := beta():
                    result = beta
            else:
                with _delta := delta():
                    result = delta
    else:
        result = _alpha

I don't think there's anything surprising there although precisely defining the semantics will be a little tricky.

--- Bruce