A "scopeguard" for Python

Alf P. Steinbach alfps at start.no
Wed Mar 3 18:18:44 CET 2010

* Robert Kern:
> On 2010-03-03 09:56 AM, Alf P. Steinbach wrote:
>> * Mike Kent:
>>> What's the compelling use case for this vs. a simple try/finally?
>> if you thought about it you would mean a simple "try/else". "finally" is
>> always executed. which is incorrect for cleanup
> Eh? Failed execution doesn't require cleanup? The example you gave is 
> definitely equivalent to the try: finally: that Mike posted.

Sorry, that's incorrect: it's not.

With correct code (mine) cleanup for action A is only performed when action A 

With incorrect code cleanup for action A is performed when A fails.

> The actions 
> are always executed in your example,

Sorry, that's incorrect.

> [The actions are] not [executed] just when an exception isn't  raised.

Sorry, that's incorrect.

>  From your post, the scope guard technique is used "to ensure some 
> desired cleanup at the end of a scope, even when the scope is exited via 
> an exception." This is precisely what the try: finally: syntax is for. 

You'd have to nest it. That's ugly. And more importantly, now two people in this 
thread (namely you and Mike) have demonstrated that they do not grok the try 
functionality and manage to write incorrect code, even arguing that it's correct 
when informed that it's not, so it's a pretty fragile construct, like goto.

> The with statement allows you to encapsulate repetitive boilerplate into 
> context managers, but a general purpose context manager like your 
> Cleanup class doesn't take advantage of this.

I'm sorry but that's pretty meaningless. It's like: "A house allows you to 
encapsulate a lot of stinking garbage, but your house doesn't take advantage of 
that, it's disgustingly clean". Hello.

Cheers & hth.,

- Alf

More information about the Python-list mailing list