[Python-ideas] ScopeGuardStatement/Defer Proposal

Manuel Barkhau mbarkhau at googlemail.com
Fri Feb 17 03:25:36 CET 2012


> Every new keyword will break code that uses that word as a regular
> name:

Ah, my bad. I had assumed that the addition of the with statement didn't
break anything and thought the only case I needed to look at was "defer:
...".

> It seems to me that defer would let you write spaghetti code in a way
> which is really difficult (if not impossible) with try blocks.

Sure people can write spaghetti code with this, who ever said it was
appropriate for everything in the world? I also wasn't aware there were
people so fond of writing try blocks, because to me they luck fugly.
Rather than wrapping all my code in a try block, I would rather write
the code that deals with peripheral cases in a block, and continue on
with the main code.

> You seem to believe that nesting is a problem to be worked around. I
> call it a feature to be encouraged.

Bingo, I don't like nesting too much.

> Is this a deliberate design choice, or an accident of implementation
> that D and Go have followed? If it is deliberate, what is the
> rationale for it?

Yes it's because of how they chose to do it and I kept it that way if
nothing else, for familiarity. But I'm sure there is some reasoning
behind it.

> Huh? That's a bizarre way to write it. A more sane equivalent would be

The example given by Doug is intended to preserve the original stack
trace of the exception that is thrown by throws.

>    def nested():
>        try:
>            throws()
>        except BaseException:
>            try:
>                cleanup()
>            except:
>                pass
>            raise

This raises the exception thrown by cleanup. If you use "raise
original_exception", the stack trace isn't preserved, which is what the
article is about. But now that you mention it, I'm not sure the defer
example I gave actually would produce the same stack trace either.

Oh well, context managers it is then I guess. Thanks for the
references Nick.

Manuel



More information about the Python-ideas mailing list