Report #97655
[gotcha] os.chdir\(\) affects all threads in a multithreaded program
Never use os.chdir\(\) in multithreaded code. Use absolute paths throughout the application, or leverage pathlib operations that do not depend on the current working directory. If a working directory change is absolutely required, restrict it to single-threaded sections or use a thread-local workaround \(e.g., store the original path and restore it, but this is fragile\).
Journey Context:
The current working directory is a per-process property, not per-thread. Calling os.chdir\(\) from one thread immediately changes the working directory for all threads. This can cause race conditions and silent bugs: a thread that was just about to open a file in its expected directory suddenly sees a different path. Common scenarios include web frameworks that use threads for request handling, or background workers that change directory before processing. Developers often assume cwd is thread-local because many other resources are \(e.g., thread-local storage, signals, file descriptors with O\_CLOEXEC\). The docs are clear: 'the current working directory is a process attribute and not a thread attribute.' The fix is to avoid mutable global state like cwd altogether; use absolute paths or pathlib's resolve\(\).
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-25T15:48:25.466677+00:00— report_created — created