A "scopeguard" for Python

Robert Kern robert.kern at gmail.com
Thu Mar 4 18:30:03 CET 2010

On 2010-03-04 11:02 AM, Alf P. Steinbach wrote:
> * Robert Kern:
>> On 2010-03-04 09:48 AM, Alf P. Steinbach wrote:
>>> * Jean-Michel Pichavant:
>>>> Alf P. Steinbach wrote:
>>>>>> 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.
>>>> You want to execute some cleanup when things go wrong, use try except.
>>>> You want to do it when things go right, use try else. You want to
>>>> cleanup no matter what happen, use try finally.
>>>> There is no need of any Cleanup class, except for some technical
>>>> alternative concern.
>>> Have you considered that your argument applies to the "with" construct?
>>> You have probably not realized that.
>>> But let me force it on you: when would you use "with"?
>> When there is a specific context manager that removes the need for
>> boilerplate.
> That's "cleanup no matter what happen".

For the "# Do stuff" block, yes. For the initialization block, you can write a 
context manager to do it either way, as necessary.

>>> Check if that case is covered by your argument above.
>>> Now that you've been told about the "with" angle, don't you think it's a
>>> kind of weakness in your argument that it calls for removing "with" from
>>> the language?
>> No, it only argues that "with Cleanup():" is supernumerary.
> I don't know what "supernumerary" means,


> but to the degree that the
> argument says anything about a construct that is not 'finally', it says
> the same about general "with".

He's ignorant of the use cases of the with: statement, true. Given only your 
example of the with: statement, it is hard to fault him for thinking that try: 
finally: wouldn't suffice.

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco

More information about the Python-list mailing list