A "scopeguard" for Python
Alf P. Steinbach
alfps at start.no
Wed Mar 3 10:56:25 EST 2010
* 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
by the way, that's one advantage:
a "with Cleanup" is difficult to get wrong, while a "try" is easy to get wrong,
as you did here
---
another general advantage is as for the 'with' statement generally
> original_dir = os.getcwd()
> try:
> os.chdir(somewhere)
> # Do other stuff
also, the "do other stuff" can be a lot of code
and also, with more than one action the try-else introduces a lot of nesting
> finally:
> os.chdir(original_dir)
> # Do other cleanup
cheers & hth.,
- alf
More information about the Python-list
mailing list