A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from http://mail.python.org/pipermail/python-list/2010-March/720506.html below:

A "scopeguard" for Python

A "scopeguard" for PythonRobert Kern robert.kern at gmail.com
Wed Mar 3 12:00:04 EST 2010
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.

-- 
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

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4