diff --git a/Lib/contextlib.py b/Lib/contextlib.py index 5b646fabca0..259194cdbbe 100644 --- a/Lib/contextlib.py +++ b/Lib/contextlib.py @@ -807,7 +807,12 @@ class chdir(AbstractContextManager): self._old_cwd = [] def __enter__(self): - self._old_cwd.append(os.getcwd()) + # try to chdir to the current cwd so that we preemptively fail if we are + # unnable to chdir back to it, see bpo-45545 + old_cwd = os.getcwd() + os.chdir(old_cwd) + + self._old_cwd.append(old_cwd) os.chdir(self.path) def __exit__(self, *excinfo): diff --git a/Misc/NEWS.d/next/Library/2021-10-26-01-22-33.bpo-45545.QvsfXK.rst b/Misc/NEWS.d/next/Library/2021-10-26-01-22-33.bpo-45545.QvsfXK.rst new file mode 100644 index 00000000000..e1fdbacfaaf --- /dev/null +++ b/Misc/NEWS.d/next/Library/2021-10-26-01-22-33.bpo-45545.QvsfXK.rst @@ -0,0 +1,2 @@ +Premptively fail in :func:`contextdir.chdir` if we can't change back to the +original directory.