import inspect
import os
from pathlib import Path


class change_directory:
    """
    A class for changing the working directory using a "with" statement.
    It takes the directory to change to as an argument. If no directory is given,
    it takes the directory of the file from which this function was called.
    """

    def __init__(self, directory: str = None) -> None:
        self.old_dir = os.getcwd()
        if directory is None:
            self.new_dir = Path(inspect.getabsfile(inspect.stack()[1][0])).parent  # type: ignore
        else:
            self.new_dir = directory

    def __enter__(self, *_) -> None:
        os.chdir(self.new_dir)

    def __exit__(self, *_) -> None:
        os.chdir(self.old_dir)

[((14, 23, 14, 34), 'os.getcwd', 'os.getcwd', ({}, {}), '()', False, 'import os\n'), ((21, 8, 21, 30), 'os.chdir', 'os.chdir', ({(21, 17, 21, 29): 'self.new_dir'}, {}), '(self.new_dir)', False, 'import os\n'), ((24, 8, 24, 30), 'os.chdir', 'os.chdir', ({(24, 17, 24, 29): 'self.old_dir'}, {}), '(self.old_dir)', False, 'import os\n'), ((16, 51, 16, 66), 'inspect.stack', 'inspect.stack', ({}, {}), '()', False, 'import inspect\n')]