Comment

Peter Hansen

I haven't tried Go yet so thanks for the summary of your experience.

I'm not convinced there's a strong use case for "defer" as I'd think if the block of code is large enough that a finally clause is "too far down" then it's already overly complex and using "defer" repeatedly throughout would make it worse. I could be convinced otherwise.

That said, you could easily make a Python context manager with similar semantics. You'd do "with deferred() as x:" and then could have x.defer(func, *args) throughout, and it would work in similar fashion at the end of the block. Might be useful some day.

Actually, I'm going to change my mind already. In some cases you have to set up a whole series of things, but in the finally clause you can't blindly tear down each of them. You need to check whether the code got to the setup (or raised an exception beforehand). The defer approach does seem like it would simplify that case as you could dispense with a bunch of conditionals in the finally clause. Hmmm... (goes to find code where this may be cleaner)

Replies

Peter Bengtsson

Yeah, a context manager and its __exit__ is maybe a good alternative to the `finally:` but it's a mess. I loooove Python but let's admit; Go wins this round :)

Ludo

I don't agree. Perhaps it was different in 2014-10, but contextlib.contextmanager makes it now quite simple to use a with statement. The only drawback I see is the extra indent, but in the end it is not that significant I find.