A "scopeguard" for Python

Alf P. Steinbach alfps at start.no
Fri Mar 5 21:32:48 EST 2010


* Robert Kern:
> On 2010-03-03 09:39 AM, Mike Kent wrote:
>> What's the compelling use case for this vs. a simple try/finally?
>>
>>     original_dir = os.getcwd()
>>     try:
>>         os.chdir(somewhere)
>>         # Do other stuff
>>     finally:
>>         os.chdir(original_dir)
>>         # Do other cleanup
> 
> A custom-written context manager looks nicer and can be more readable.
> 
> from contextlib import contextmanager
> import os
> 
> @contextmanager
> def pushd(path):
>     original_dir = os.getcwd()
>     os.chdir(path)
>     try:
>         yield
>     finally:
>         os.chdir(original_dir)
> 
> 
> with pushd(somewhere):
>     ...
> 
> 
> I don't think a general purpose ScopeGuard context manager has any such 
> benefits over the try: finally:, though.

class pushd( Cleanup ):
     def __init__( self, path ):
         original_dir = os.getcwd()
         os.chdir( path )
         self._actions.append( lambda: os.chdir( original_dir ) )


Disclaimer: haven't tested this, but it just occurred to me that for such small 
init/cleanup wrappers the Cleanup class provides a nice alternative to 
@contextmanager, as above: fewer lines, and perhaps even more clear code. :-)


Cheers,

- Alf



More information about the Python-list mailing list