__del__ is called when an instance is to be destroyed. So when you instantiate this class, the current working directory is stored in the instance attribute, and then, well, os.chdir is called. When an instance is destroyed (for some reason), the current directory changes to its old value.
This looks a little wrong for me. As far as I know, you should call the parent __del__ in your __del__ override, so it should be something like this:
class Chdir(object): def __init__(self, new_path): self.saved_path = os.getcwd() os.chdir(new_path) def __del__(self): os.chdir(self.saved_path) super(Chdir, self).__del__()
That is, if I am missing something, of course.
(By the way, can you do the same with the contextmanager?)
source share