Check-then-create directory
Several worker processes call ensure_dir() at startup. Occasionally one crashes with FileExistsError. Why?
import os def ensure_dir(path: str) -> str: """Create the directory if it doesn't exist yet.""" if not os.path.exists(path): os.makedirs(path) return pathShow answer
line 7 · Race condition
This is a time-of-check to time-of-use race. Two processes can both see that the path doesn't exist, then both call makedirs, and the slower one raises FileExistsError. Make the operation itself idempotent instead of checking first.
os.makedirs(path, exist_ok=True)Interview follow-up: A good answer generalizes: prefer atomic operations (exist_ok, O_EXCL, INSERT ... ON CONFLICT) over check-then-act.