Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 676
Daryl Spitzer Avatar asked Oct 03 '08 22:10

Daryl Spitzer


People also ask

How do Decorators work in C++?

When you apply a decorator to a class or a class member, you are actually calling a function that is going to receive details of what is being decorated, and the decorator implementation will then be able to transform the code dynamically, adding extra functionality, and reducing boilerplate code.

What are the parameter(s) passed to the decorator?

The parameter (s) passed to the decorator will depend on where the decorator will be used. The first parameter is commonly called target. The sealed decorator will be used only on class declarations, so your function will receive a single parameter, the target, which will be of type Function.

When should I use decorators in Python?

When to Use a Decorator in Python You'll use a decorator when you need to change the behavior of a function without modifying the function itself. A few good examples are when you want to add logging, test performance, perform caching, verify permissions, and so on. You can also use one when you need to run the same code on multiple functions.

When should I use a decorator?

You'll use a decorator when you need to change the behavior of a function without modifying the function itself. A few good examples are when you want to add logging, test performance, perform caching, verify permissions, and so on.


1 Answers

The answer for a decorator has been given; it works at the function definition stage as requested.

With Python 2.5+, you also have an option to do that at the function call stage using a context manager:

from __future__ import with_statement # needed for 2.5 ≤ Python < 2.6 import contextlib, os  @contextlib.contextmanager def remember_cwd():     curdir= os.getcwd()     try: yield     finally: os.chdir(curdir) 

which can be used if needed at the function call time as:

print "getcwd before:", os.getcwd() with remember_cwd():     walk_around_the_filesystem() print "getcwd after:", os.getcwd() 

It's a nice option to have.

EDIT: I added error handling as suggested by codeape. Since my answer has been voted up, it's fair to offer a complete answer, all other issues aside.

like image 186
tzot Avatar answered Sep 20 '22 19:09

tzot