On Wed, 15 Sept 2021 at 08:02, Christian Heimes <christian@python.org> wrote:
The "better way" to handle current working directory is to use the modern *at() variants of syscalls, e.g. openat() instead open(). The variants take an additional file descriptor dirfd that is used as the current working directory for the syscall.
Just a somewhat off-topic note, but dir_fd arguments are only supported on Unix, and the functionality only appears to be present at the NT Kernel level on Windows, not in the Windows API. So this is only a "better" approach if you are writing Unix-only code. Conversely, the most significant cases where I've wanted a "set the current directory" context manager are to run some code with a temporary directory as CWD, but then make sure I don't leave that as the CWD, because Windows won't let me delete a directory that's the CWD of a running process, so my cleanup will fail if I don't reset the CWD. So the proposed context manager is probably more beneficial for Windows users. Paul