On 2020-02-08 6:53 p.m., Bruce Leban wrote:

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
                with _delta := delta():
                    result = delta
        result = _alpha

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

I'd expect it to go more like

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

and even then I might've messed something up here. This seems about as hard to transform as the halting problem tho, at face value.

--- Bruce

Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-leave@python.org
Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/QKG6VAUFM44EBUMFUVDAMWK2WYBBKKUN/
Code of Conduct: http://python.org/psf/codeofconduct/