[Python-ideas] ScopeGuardStatement/Defer Proposal

Sven Marnach sven at marnach.net
Fri Feb 17 18:14:01 CET 2012

Steven D'Aprano schrieb am Fr, 17. Feb 2012, um 12:25:41 +1100:
> Why in reverse order? This is unintuitive.
> [...]
> 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?

Basically any cleanup mechanism I know of does the cleanups in the
reverse order as the initialisations, be it destructor calls in C++,
defer handlers in Go or nested 'with' statements in Python.  Since the
later initialised objects might depend on the previously defined
objects, this is also the only sane choice.

> With defer, that structure is gone. The reader has to try to
> recreate the execution order in their head. That is an enormous
> negative.

I think "defer" has some definite advantages over try/except as far as
readability is concerned.  It places the cleanup code at the position
the necessity for the cleanup occurs, and not way down in the code.
Python's "with" statement does a similar thing, but it gets difficult
to handle as soon as you try to *conditionally* add a cleanup handler
-- we had this discussion before, and it lead to Nick's contextlib2.


More information about the Python-ideas mailing list