On 2020-02-08 6:53 p.m., Bruce Leban wrote:
On Sat, Feb 8, 2020 at 1:22 PM Chris Angelico <firstname.lastname@example.org mailto:email@example.com> wrote:
On Sun, Feb 9, 2020 at 8:04 AM Random832 <firstname.lastname@example.org <mailto:email@example.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:
with gamma() as _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.
Python-ideas mailing list -- firstname.lastname@example.org To unsubscribe send an email to email@example.com https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://firstname.lastname@example.org/message/QKG6VA... Code of Conduct: http://python.org/psf/codeofconduct/