[Python-ideas] chdir context manager (original) (raw)
Eli Bendersky eliben at gmail.com
Sat Jan 19 16:53:12 CET 2013
- Previous message: [Python-ideas] chdir context manager
- Next message: [Python-ideas] chdir context manager
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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.makearchive):
savecwd = os.getcwd() try: foo() finally: os.chdir(savecwd) I suggest this deserves a context manager: with savedcwd(): 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.savedcwd, based on os.fchdir. The patch also adds os.chdir to os.supportsdirfd 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>
- Previous message: [Python-ideas] chdir context manager
- Next message: [Python-ideas] chdir context manager
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]