[Python-ideas] chdir context manager

Christian Heimes christian at python.org
Sat Jan 19 16:33:44 CET 2013


Am 19.01.2013 11:10, schrieb Daniel Shahaf:
> The following is a common pattern (used by, for example,
> shutil.make_archive):
> 
>     save_cwd = os.getcwd()
>     try:
>         foo()
>     finally:
>         os.chdir(save_cwd)
> 
> I suggest this deserves a context manager:
> 
>     with saved_cwd():
>         foo()

-1 from me, too.

chdir() is not a safe operation because if affects the whole process.
You can NOT make it work properly and safe in a multi-threaded
environment or from code like signal handlers.

The Open Group has acknowledged the issue and added a new set of
functions to POSIX.1-2008 in order to address the issue. The *at()
variants of functions like open() take an additional file descriptor as
first argument. The fd must refer to a directory and is used as base for
relative paths. Python 3.3 supports the new *at() feature.

Christian



More information about the Python-ideas mailing list