pythondecoratorcwd

How do I write a decorator that restores the cwd?


How do I write a decorator that restores the current working directory to what it was before the decorated function was called? In other words, if I use the decorator on a function that does an os.chdir(), the cwd will not be changed after the function is called.


Solution

  • The path.py module (which you really should use if dealing with paths in python scripts) has a context manager:

    subdir = d / 'subdir' #subdir is a path object, in the path.py module
    with subdir:
      # here current dir is subdir
    
    #not anymore
    

    (credits goes to this blog post from Roberto Alsina)