DEV Community

Discussion on: Changing Directory with a Python Context Manager

Collapse
 
waylonwalker profile image
Waylon Walker

Great use case for a context manager. Outside of opening files context managers are far too underutilized.

There is also an alternative class based syntax that you may run into on occasion.

class set_directory(object):
      """Sets the cwd within the context

      Args:
          path (Path): The path to the cwd
      """
     def __init__(self, path: Path):
          self.path = path
          self.origin = Path().absolute()

     def __enter__(self):
            os.chdir(self.path)
     def __exit__(self):
            os.chdir(self.origin)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
teckert profile image
Thomas Eckert

Great point! Thank you for providing a full class example. I'm sure people will find it useful to reference!