A "scopeguard" for Python
robert.kern at gmail.com
Wed Mar 3 18:09:11 CET 2010
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. The actions are always
executed in your example, not just when an exception isn't raised.
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. 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
"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