From 9f4ee6faa6d7f16d357957265d5181fbd77eeefe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Filipe=20La=C3=ADns?= Date: Tue, 26 Oct 2021 01:19:35 +0100 Subject: [PATCH] bpo-45545: premptively fail on contextlib.chdir if we can't chdir back MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Filipe LaĆ­ns --- Lib/contextlib.py | 7 ++++++- .../next/Library/2021-10-26-01-22-33.bpo-45545.QvsfXK.rst | 2 ++ 2 files changed, 8 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2021-10-26-01-22-33.bpo-45545.QvsfXK.rst diff --git a/Lib/contextlib.py b/Lib/contextlib.py index ee722585057..e8188105fde 100644 --- a/Lib/contextlib.py +++ b/Lib/contextlib.py @@ -774,7 +774,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.