Sphere
Log in Join
☆ 4

pathlib / operator throws away the left side when right side is absolute

Small one that surprised me. Path('/data') / '/raw/file.csv' gives PosixPath('/raw/file.csv') — the first part is completely discarded. I expected /data/raw/file.csv. Python 3.11. Is this documented behavior? I couldn't find it in the pathlib docs and it caused a real bug where our app read from the wrong directory. My inputs come from a config where absolute-looking paths sometimes show up unexpectedly. We chose to reject at config-load time, which surfaced a bad value nobody had noticed.

⚑ Report

4 replies

☆ 0
C cactus ·2026-10-09#1

It is documented, sort of — pathlib follows POSIX rules where an absolute right operand replaces the left entirely. It's identical to os.path.join('/data', '/raw/file.csv') which also returns '/raw/file.csv'. Surprising the first time you see it, but intentional and consistent with the shell.

⚑ Report
☆ 0
N null ·2026-10-12#2

Okay, so I need to defend against it. What's the cleanest way — lstrip the slash from the right operand? I worry that .lstrip('/') would also break Windows-style UNC paths or root-relative URLs. Is there a more principled approach? We validate at config load and reject absolute values now, which caught a bad setting we'd missed.

⚑ Report
☆ 0
D duct90 ·2026-10-24#3

Don't lstrip blindly. Use Path(right).relative_to(Path(right).anchor) when it's absolute, or just check if Path(right).is_absolute() and decide your policy explicitly: strip, reject, or accept it as an intentional override. Sometimes you actually want the override, so making that choice visible in code is better.

⚑ Report
☆ 0
V vector ·2026-11-03#4

We had a bug exactly like this where a config value with a leading slash made the app read from /tmp instead of the configured data dir. Now we validate config paths at load time and reject absolute values unless a flag explicitly says they're intentional. Saves a lot of head-scratching six months later.

⚑ Report
Log in to reply.