Skip to content

bpo-25625: add contextlib.chdir #28271

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Oct 19, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions Doc/library/contextlib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,18 @@ Functions and classes provided:
.. versionadded:: 3.5


.. function:: chdir(path)

Non thread-safe context manager to change the current working directory.

This is a simple wrapper around :func:`~os.chdir`, it changes the current
working directory upon entering and restores the old one on exit.

This context manager is :ref:`reentrant <reentrant-cms>`.

.. versionadded:: 3.11


.. class:: ContextDecorator()

A base class that enables a context manager to also be used as a decorator.
Expand Down Expand Up @@ -900,8 +912,8 @@ but may also be used *inside* a :keyword:`!with` statement that is already
using the same context manager.

:class:`threading.RLock` is an example of a reentrant context manager, as are
:func:`suppress` and :func:`redirect_stdout`. Here's a very simple example of
reentrant use::
:func:`suppress`, :func:`redirect_stdout` and :func:`chdir`. Here's a very
simple example of reentrant use::

>>> from contextlib import redirect_stdout
>>> from io import StringIO
Expand Down
19 changes: 18 additions & 1 deletion Lib/contextlib.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Utilities for with-statement contexts. See PEP 343."""
import abc
import os
import sys
import _collections_abc
from collections import deque
Expand All @@ -9,7 +10,8 @@
__all__ = ["asynccontextmanager", "contextmanager", "closing", "nullcontext",
"AbstractContextManager", "AbstractAsyncContextManager",
"AsyncExitStack", "ContextDecorator", "ExitStack",
"redirect_stdout", "redirect_stderr", "suppress", "aclosing"]
"redirect_stdout", "redirect_stderr", "suppress", "aclosing",
"chdir"]


class AbstractContextManager(abc.ABC):
Expand Down Expand Up @@ -754,3 +756,18 @@ async def __aenter__(self):

async def __aexit__(self, *excinfo):
pass


class chdir(AbstractContextManager):
"""Non thread-safe context manager to change the current working directory."""

def __init__(self, path):
self.path = path
self._old_cwd = []

def __enter__(self):
self._old_cwd.append(os.getcwd())
os.chdir(self.path)

def __exit__(self, *excinfo):
os.chdir(self._old_cwd.pop())
43 changes: 43 additions & 0 deletions Lib/test/test_contextlib.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Unit tests for contextlib.py, and other context managers."""

import io
import os
import sys
import tempfile
import threading
Expand Down Expand Up @@ -1080,5 +1081,47 @@ def test_cm_is_reentrant(self):
1/0
self.assertTrue(outer_continued)


class TestChdir(unittest.TestCase):
def test_simple(self):
old_cwd = os.getcwd()
target = os.path.join(os.path.dirname(__file__), 'data')
assert old_cwd != target

with chdir(target):
assert os.getcwd() == target
assert os.getcwd() == old_cwd

def test_reentrant(self):
old_cwd = os.getcwd()
target1 = os.path.join(os.path.dirname(__file__), 'data')
target2 = os.path.join(os.path.dirname(__file__), 'ziptestdata')
assert old_cwd not in (target1, target2)
chdir1, chdir2 = chdir(target1), chdir(target2)

with chdir1:
assert os.getcwd() == target1
with chdir2:
assert os.getcwd() == target2
with chdir1:
assert os.getcwd() == target1
assert os.getcwd() == target2
assert os.getcwd() == target1
assert os.getcwd() == old_cwd

def test_exception(self):
old_cwd = os.getcwd()
target = os.path.join(os.path.dirname(__file__), 'data')
assert old_cwd != target

try:
with chdir(target):
assert os.getcwd() == target
raise RuntimeError()
except RuntimeError:
pass
assert os.getcwd() == old_cwd


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Added :func:`~contextlib.chdir` context manager to change the current working
directory and then restore it on exit. Simple wrapper around :func:`~os.chdir`.