Skip to content

What is tmp_path equivalent for tmpdir.as_cwd() ? #10437

Answered by The-Compiler
pllim asked this question in Q&A
Discussion options

You must be logged in to vote

No pre-made pathlib equivalent exists. You could use pytest's monkeypatch fixture:

monkeypatch.chdir(tmp_path)

or alternatively, something like this:

old_cwd = pathlib.Path.cwd()
os.chdir(path)
yield
os.chdir(old_cwd)

If you really need a context manager (doesn't look like you do here), it'd look something like this:

@contextlib.contextmanager
def change_cwd(path: pathlib.Path) -> Iterator[None]:
    old_cwd = pathlib.Path.cwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(old_cwd)

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by The-Compiler
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants