<p>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 <code>os.chdir()</code>, the cwd will not be changed after the function is called.</p>

```
```
def preserve_cwd(function):
   def decorator(*args, **kwargs):
      cwd = os.getcwd()
      result = function(*args, **kwargs)
      os.chdir(cwd)
      return result
   return decorator
```
```
Here's how it's used:
```
```
@preserve_cwd
def test():
  print 'was:',os.getcwd()
  os.chdir('/')
  print 'now:',os.getcwd()

>>> print os.getcwd()
/Users/dspitzer
>>> test()
was: /Users/dspitzer
now: /
>>> print os.getcwd()
/Users/dspitzer
```
```