TATECHATLAS
◎ English
Programming / Tip

PurePath versus Path: when path math is not filesystem truth

Use PurePath-family classes for portable, I/O-free path manipulation and Path/PosixPath/WindowsPath for filesystem-backed work. Do not treat lexical normalization as proof that a target exists, resolves through symlinks, or is contained.

On this page

Choose PurePath, PurePosixPath, or PureWindowsPath when you only need path structure: joining, splitting, comparing, or manipulating Windows-style paths on Unix. Choose Path, PosixPath, or WindowsPath when you need real filesystem behavior. PurePath collapses spurious slashes and single dots, but leaves '..' and leading double slashes intact because resolving them naively would change meaning for symlinks and UNC paths. Concrete path classes can only be instantiated for the current platform flavour, and their system-call methods can raise OSError when the underlying call fails. Before trusting a path for existence, containment, symlink targets, or safety, call resolve() or filesystem checks such as exists(), is_file(), is_dir(), or is_symlink() as appropriate.

Choose the right path class for the job

pathlib was added in Python 3.4 and splits path classes into pure paths and concrete paths. Pure paths provide computational operations without I/O; concrete paths inherit from pure paths and add system-call operations. If you are unsure, Path is usually the right default because it instantiates the concrete path for the platform the code is running on.

Use PurePosixPath or PureWindowsPath when you must manipulate a foreign flavour, such as Windows paths on a Unix machine, or when you want code that only manipulates path strings and never touches the OS. You cannot instantiate a WindowsPath while running on Unix, but you can instantiate PureWindowsPath. Pure paths also implement os.PathLike, so they can be passed anywhere the interface is accepted.

In the example above, PureWindowsPath parses a Windows-style path and extracts parent, stem, suffix, and parts without any system call. This works identically whether the script runs on Linux, macOS, or Windows. Path('setup.py') instead instantiates the concrete class matching the host OS, so type(q) prints PosixPath on Unix or WindowsPath on Windows.

from pathlib import PurePath, PurePosixPath, PureWindowsPath, Path

# PureWindowsPath works on any OS for structural manipulation
p = PureWindowsPath(r'C:\Users\alice\Documents\report.pdf')
print(p.parent)          # C:\Users\alice\Documents
print(p.stem)            # report
print(p.suffix)          # .pdf
print(p.parts)           # ('C:\\', 'Users', 'alice', 'Documents', 'report.pdf')

# Path instantiates the concrete class for the running platform
q = Path('setup.py')
print(type(q))           # <class 'pathlib.PosixPath'> on Linux, <class 'pathlib.WindowsPath'> on Windows

Understand why '..' is not collapsed

PurePath collapses repeated slashes and single dots, but it deliberately leaves double dots and leading double slashes intact. That is not a bug; a naive collapse would turn 'foo/../bar' into 'bar', which is wrong when foo is a symbolic link to another directory.

The same caution applies to leading double slashes, because they can be meaningful in UNC or platform-specific path semantics. Lexical normalization is therefore only a structural operation, not a resolution of the path through the filesystem.

The example demonstrates four rules with concrete inputs. PurePosixPath('foo//bar') collapses to 'foo/bar' and PurePosixPath('foo/./bar') collapses to 'foo/bar'. But PurePosixPath('foo/../bar') stays as 'foo/../bar' and PurePosixPath('//foo/bar') keeps the leading double slash. The Windows flavour follows the same logic: backslash-separated double dots remain, and UNC prefixes like \\server\share are preserved.

from pathlib import PurePosixPath, PureWindowsPath

# Spurious slashes and single dots are collapsed
print(PurePosixPath('foo//bar'))       # foo/bar
print(PurePosixPath('foo/./bar'))      # foo/bar

# Double dots are NOT collapsed
print(PurePosixPath('foo/../bar'))     # foo/../bar

# Leading double slashes are NOT collapsed
print(PurePosixPath('//foo/bar'))      # //foo/bar

# Same rules apply to Windows flavour
print(PureWindowsPath(r'foo\..\bar'))  # foo\..\bar
print(PureWindowsPath(r'\\server\share'))  # \\server\share

Use concrete paths only when filesystem truth is needed

Concrete paths are subclasses of pure paths and add methods that perform system calls. Path instantiates the concrete path for the current platform, either PosixPath or WindowsPath. PosixPath and WindowsPath are concrete subclasses, but only the flavour matching the running system can be instantiated for system calls; since Python 3.13, the mismatched flavour raises UnsupportedOperation instead of NotImplementedError. Because UnsupportedOperation inherits from NotImplementedError, existing code that catches NotImplementedError still handles the newer error, while code that specifically catches UnsupportedOperation can distinguish the two cases.

Some concrete methods can raise OSError when a system call fails, for example because the path does not exist. That is a feature of filesystem-backed work, not a reason to use PurePath for existence checks.

Use Path when you need iterdir(), glob(), open(), exists(), is_file(), is_dir(), stat(), resolve(), or similar operations. Use PurePath when you need path structure only and want to avoid accidental I/O.

The example creates a temporary directory tree, then uses Path methods to query the real filesystem. exists(), is_dir(), and is_file() return booleans based on actual directory entries. A missing path returns False rather than raising an error. The PurePosixPath constructed from the same string can extract .name but has no exists() method, confirming that pure paths are structurally limited.

from pathlib import Path, PurePosixPath
import tempfile, os

# Create a temporary directory with a known structure
with tempfile.TemporaryDirectory() as tmpdir:
    base = Path(tmpdir)
    (base / 'sub').mkdir()
    (base / 'sub' / 'file.txt').write_text('hello')

    # Concrete operations query the real filesystem
    print((base / 'sub').exists())        # True
    print((base / 'sub').is_dir())        # True
    print((base / 'sub' / 'file.txt').is_file())  # True
    print((base / 'missing').exists())    # False

    # Pure path cannot answer these questions
    pp = PurePosixPath(base / 'sub' / 'file.txt')
    print(pp.name)                        # file.txt
    # pp.exists() would raise AttributeError

Apply the limits before trusting path results

Pure paths do not perform I/O and cannot prove that a path exists, is a directory, is a symlink, or resolves through symlinks. A lexical result such as PurePosixPath('foo/../bar') is not a promise about the filesystem.

Concrete Path results are also not unconditional proof: methods can raise OSError, and resolve() is the filesystem-aware step that follows symlinks. For containment or safety decisions, resolve first and then compare or check the resolved path.

Path operations should not be treated as a substitute for explicit checks. If a decision depends on existence, target identity, or containment, verify with exists(), is_file(), is_dir(), is_symlink(), resolve(), or an equivalent filesystem check before acting.

The example creates a symlink 'link' pointing to 'real_dir'. Lexically, PurePosixPath sees 'link/sub' as a child of the base directory. After resolve(), the path becomes the real directory followed by 'sub', revealing the true target. Note that the resolved path may differ from the tmpdir string returned by tempfile.TemporaryDirectory() because resolve() expands all symlinks in the path; on macOS, for instance, /var is a symlink to /private/var, so the resolved output shows /private/var/folders/... instead of /var/folders/.... The relative_to() check then confirms containment against the resolved directory. Without resolve(), a symlink could redirect access outside the intended subtree, making the lexical check unsafe for authorization decisions.

from pathlib import Path, PurePosixPath
import tempfile, os

with tempfile.TemporaryDirectory() as tmpdir:
    base = Path(tmpdir)
    (base / 'real_dir').mkdir()
    (base / 'link').symlink_to(base / 'real_dir')

    # Lexical containment says 'link/sub' is under base
    lexical = PurePosixPath(base / 'link' / 'sub')
    print(lexical.parts)  # ('/', ..., 'link', 'sub')

    # resolve() follows the symlink to the actual target
    resolved = (base / 'link' / 'sub').resolve()
    # The resolved path reflects the platform's real temp directory.
    # On macOS, /var is a symlink to /private/var, so resolve() may
    # return /private/var/folders/.../real_dir/sub rather than the
    # tmpdir string shown by tempfile.TemporaryDirectory().
    print(resolved)       # <resolved temp dir>/real_dir/sub

    # Containment check after resolve
    target = base / 'real_dir'
    try:
        resolved.relative_to(target)
        print('inside real_dir')
    except ValueError:
        print('outside real_dir')

Applicability

  • Is the task only structural path manipulation, or does it require real filesystem behavior?
  • Will the path be used on a platform different from the one running the code?
  • Does the path contain '..', leading double slashes, or symlink-sensitive components?
  • Is the decision based on existence, target identity, containment, or safety rather than string shape?
  • Are you willing to call resolve() or filesystem checks before acting?

This is not a guarantee that every path operation is safe or that resolve() is always sufficient; resolve() follows symlinks and can still fail or be platform-dependent. PurePath remains useful for portability and structure, but it is not a replacement for os.path in every case and must not be used as proof of filesystem truth.

Sources

  1. Python: json ↗
  2. Python: pathlib ↗
Back to top ↑