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
            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.

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
            else:
                with delta() as _delta:
                    result = _delta
    else:
        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
https://mail.python.org/mailman3/lists/python-ideas.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/