(original) (raw)
On Sat, Jan 19, 2013 at 2:10 AM, Daniel Shahaf <d.s@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
�