PurePosixPath Walks Virtual Trees

Build and join pure path objects over in-memory trees: PurePosixPath does string algebra with no filesystem access, so manifests and reports stay deterministic.

PythonData Integrity

Code

pythonsnippet
31 lines
from pathlib import PurePosixPath

# 纯路径树:只操作字符串,不触碰文件系统
TREE = {
    "app": {
        "api": {"routes.py": 4, "deps.py": 2},
        "models": {"user.py": 3, "order.py": 5},
        "settings.toml": 1,
    },
    "tests": {"test_api.py": 2},
}


def walk(node, prefix=PurePosixPath()):
    for name, value in node.items():
        path = prefix / name          # / 运算符做路径拼接
        if isinstance(value, dict):
            yield path, None
            yield from walk(value, path)
        else:
            yield path, value


for path, size in walk(TREE):
    suffix = f" ({size} KB)" if size is not None else "/"
    print(f"{path}{suffix}")

# 纯路径支持常用谓词:后缀、父级、相对化
manifest = PurePosixPath("app/api/routes.py")
print("suffix:", manifest.suffix, "parent:", manifest.parent)
print("relative to app:", manifest.relative_to("app"))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

app/
app/api/
app/api/routes.py (4 KB)
app/api/deps.py (2 KB)
app/models/
app/models/user.py (3 KB)
app/models/order.py (5 KB)
app/settings.toml (1 KB)
tests/
tests/test_api.py (2 KB)
suffix: .py parent: app/api
relative to app: api/routes.py

Inside the snippet

PurePosixPath Walks Virtual Trees reduces to the function walk.

Repetition is confined to for name, value in node.items() — the rest of the file is straight-line.

Using it

The primary signature is def walk(node, prefix=PurePosixPath()

The demo output is labeled (suffix:, relative to app:), so every printed line maps back to its originating operation.

walk is the public entry point; everything else in the file exists to support it.

Key statements

def walk(node, prefix=PurePosixPath()):
    for name, value in node.items():
        path = prefix / name          # / 运算符做路径拼接
        if isinstance(value, dict):
            yield path, None
            yield from walk(value, path)
        else:
            yield path, value

Interactive Tools for This Topic

FAQ

Does this work in a bare project with no dependencies file?
Yes — a bare project runs it as-is, since nothing needs declaring. Every import resolves inside the standard library — `pathlib`. The file defines `walk` at load time.