Choose pathlib lexical paths versus resolved paths in a local tool
Quick answer
Path spelling and resolved target answer different local-tool questions: one is what the caller typed, the other follows filesystem links.
Example
The temporary fixture makes a directory symlink. link.name preserves the lexical display name, while link.resolve() identifies target. The assertion demonstrates why a status message and a target-identity check may intentionally use different values.
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as d:
base = Path(d)
target = base / 'target'
target.mkdir()
link = base / 'link'
link.symlink_to(target, target_is_directory=True)
assert str(link).endswith('link') and link.resolve() == target.resolve()
print(f'lexical={link.name} resolved={link.resolve().name}')
Expected stdout:
lexical=link resolved=target
Reading the result
Resolution can fail or change meaning when links are broken or permissions differ. Do not resolve merely for prettier output; resolve only when the tool rule is about the target.
For a destructive operation, target identity may matter more than display spelling; for a diagnostic, the original argument is often kinder. Make the choice at each call site explicit.
The symlink lives inside TemporaryDirectory, so the comparison has no dependence on a user path. Its only purpose is to make the lexical-versus-target distinction observable.
Sources
- Python pathlib documentation
Prepared with AI assistance. The example uses synthetic data; its stated limits apply.
Comments
Post a Comment