[Python-ideas] chdir context manager

Oleg Broytman phd at phdru.name
Sat Jan 19 15:02:19 CET 2013


On Sat, Jan 19, 2013 at 01:46:26PM +0000, Vinay Sajip <vinay_sajip at yahoo.co.uk> wrote:
> Daniel Shahaf <d.s at ...> writes:
> 
> > Joao S. O. Bueno wrote on Sat, Jan 19, 2013 at 10:17:57 -0200:
> > > with temp_dir("/tmp"):
> > >     # things that perform in  /tmp
> > > # directory is restored.
> > 
> > +1
> 
> I implemented this in distlib as:
> 
> @contextlib.contextmanager
> def chdir(d):
>     cwd = os.getcwd()
>     try:
>         os.chdir(d)
>         yield
>     finally:
>         os.chdir(cwd)
> 
> which could perhaps be placed in shutil, so usage would be:
> 
> with shutil.chdir('new_dir'):
>     # work with new_dir as current dir
> # directory restored when you get here.

   Pushd or pushdir would be a better name, IMHO.

https://en.wikipedia.org/wiki/Pushd_and_popd

   Quite a known pair of names.

Oleg.
-- 
     Oleg Broytman            http://phdru.name/            phd at phdru.name
           Programmers don't die, they just GOSUB without RETURN.



More information about the Python-ideas mailing list