Non thread-safe context manager to change the current working directory.
| 73 | |
| 74 | # borrowed from py3.11 |
| 75 | class chdir(contextlib.AbstractContextManager): # noqa: N801 |
| 76 | """Non thread-safe context manager to change the current working directory.""" |
| 77 | |
| 78 | def __init__(self, path: str | Path): |
| 79 | """Prepare contextmanager. |
| 80 | |
| 81 | Args: |
| 82 | path: the path to change to |
| 83 | """ |
| 84 | self.path = path |
| 85 | self._old_cwd = [] |
| 86 | |
| 87 | def __enter__(self): |
| 88 | """Save current directory and perform chdir.""" |
| 89 | self._old_cwd.append(Path.cwd()) |
| 90 | os.chdir(self.path) |
| 91 | |
| 92 | def __exit__(self, *excinfo): |
| 93 | """Change back to previous directory on stack. |
| 94 | |
| 95 | Args: |
| 96 | excinfo: sys.exc_info captured in the context block |
| 97 | """ |
| 98 | os.chdir(self._old_cwd.pop()) |
| 99 | |
| 100 | |
| 101 | @dataclasses.dataclass |
no outgoing calls