From 0413dd881c4905b7c7fdf20eef9fb78a6d5cb33d Mon Sep 17 00:00:00 2001 From: wei-juncheng Date: Sun, 15 Jun 2025 13:25:49 +0800 Subject: [PATCH] Document behavior of Path.resolve() regarding current working directory and existence checks --- Doc/library/pathlib.rst | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Doc/library/pathlib.rst b/Doc/library/pathlib.rst index 86351e65dc4ed6..435aabeeb9a90c 100644 --- a/Doc/library/pathlib.rst +++ b/Doc/library/pathlib.rst @@ -982,6 +982,24 @@ Expanding and resolving paths strict mode, and no exception is raised in non-strict mode. In previous versions, :exc:`RuntimeError` is raised no matter the value of *strict*. + .. note:: + + Even with ``strict=False``, ``Path.resolve()`` internally calls + :func:`os.getcwd` to obtain the current working directory (cwd). + If the cwd has been removed (for example, by unlinking it externally), + :func:`os.getcwd` will raise :exc:`FileNotFoundError`, causing + ``resolve()`` to fail. + + Therefore: + + - Do **not** rely solely on ``Path.exists()`` as a pre-check for + ``resolve()``: ``exists()`` only reflects the existence of the + *target* path in the filesystem, and does not detect whether the cwd + has been deleted. + - In multi-threaded or multi-process environments, a successful + ``exists()`` check may still race with filesystem changes that occur + before calling ``resolve()``. + .. method:: Path.readlink()