On Sat, Feb 8, 2020, at 17:14, Soni L. wrote:
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 wrote:
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:
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
My own expectation, for what it's worth, would be something like
try: _alpha_set = _beta_set = _gamma_set = _delta_set = False result = (_alpha_cm := alpha(), _alpha_set:=True).__enter__() and ((same transform for beta) if (...gamma) else (...delta)) finally: try: if _delta_set: _delta_cm.__exit__() finally: try: if _gamma_set: _gamma_cm.__exit__() finally: ...
but this is more of a mess than I originally thought to define in scenarios with multiple and/or conditionally-used context managers. It's also tempting to try to define a way to, e.g. only include it in scope for the evaluation of the condition in if statements and while loops.