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, 'os.getcwd', 'os.getcwd', False, 'import os\n'), (21, 'os.chdir', 'os.chdir', False, 'import os\n'), (24, 'os.chdir', 'os.chdir', False, 'import os\n'), (16, 'inspect.stack', 'inspect.stack', False, 'import inspect\n')]