[Python-ideas] chdir context manager

Eli Bendersky eliben at gmail.com
Sat Jan 19 16:53:12 CET 2013


On Sat, Jan 19, 2013 at 2:10 AM, Daniel Shahaf <d.s at daniel.shahaf.name>wrote:

> 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()
>
> Initial feedback on IRC suggests shutil as where this functionality
> should live (other suggestions were made, such as pathlib).  Hence,
> attached patch implements this as shutil.saved_cwd, based on os.fchdir.
>
> The patch also adds os.chdir to os.supports_dir_fd and documents the
> context manager abilities of builtins.open() in its reference.
>
> Thoughts?
>
>
I don't think that every trivial convenience context manager should be
added to the standard library. It's just "yet another thing to look up". As
the discussion shows, the semantics of such a context manager are unclear
(does it do the change-dir itself or does the user code do it?), which
makes it even more important to look-up once you see it.

Moreover, this kind of a pattern is too general and specializing it for
each use case is burdensome. I've frequently written similar context
managers for other uses. The pattern is:

saved = save_call()
yield
restore_call(saved)

You can have it for chdir, for sys.path, for seek position in stream, for
anything really where it may be useful to do some operation with a
temporary state.

Eli
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130119/93870d87/attachment.html>


More information about the Python-ideas mailing list