Build a platform-neutral cache path
Build a platform-neutral cache path
A cache key is often a sequence of logical components: cache area, package name, version, and filename. It should not depend on whichever operating system happens to run the program. This example builds that sequence with PurePosixPath and PureWindowsPath, then uses as_posix() to emit one stable, slash-separated representation for logs, manifests, or cache metadata.
The input components are cache, demo, v1, and index.json. Both path flavours preserve them as four parts, which the assertions check. The two printed results are therefore the same cache/demo/v1/index.json, even though str(PureWindowsPath(...)) would use Windows separators. PurePath classes perform lexical path manipulation only; they do not create directories or confirm that a cache location exists.
Do not pass an untrusted absolute component to a path join without validating it: an absolute later segment can discard earlier segments. Also, a logical cache key is not a guarantee of a safe filesystem location, collision resistance, or portable file permissions. pathlib and pure paths were added in Python 3.4. See the pathlib documentation for path flavours and joining semantics.
AI assistance disclosure: This article was drafted with AI assistance and should be reviewed in the context of its application.
from pathlib import PurePosixPath, PureWindowsPath
posix = PurePosixPath("cache") / "demo" / "v1" / "index.json"
windows = PureWindowsPath("cache") / "demo" / "v1" / "index.json"
assert posix.parts == ("cache", "demo", "v1", "index.json")
assert windows.parts == ("cache", "demo", "v1", "index.json")
print(posix.as_posix())
print(windows.as_posix())
cache/demo/v1/index.json
cache/demo/v1/index.json
Comments
Post a Comment