Skip to content

Atomic write

atomic_write

Durable whole-file replacement primitive.

A whole-file rewrite must never leave a half-written module on disk. This module writes the new bytes to a temporary sibling located in the SAME directory as the target (so os.replace stays on one filesystem and is therefore atomic), fsyncs it, swaps it over the target, then best-effort fsyncs the containing directory.

The primitive is deliberately a leaf: it knows nothing about operations, checksums or scope resolution — it takes an already-resolved absolute :class:~pathlib.Path and the bytes to write.

atomic_replace(target, data)

Replace target with data atomically and durably.

The original permission bits are preserved. On any failure the target is left untouched and no temp sibling survives.

Source code in packages/axm-edit/src/axm_edit/core/atomic_write.py
Python
def atomic_replace(target: Path, data: bytes) -> None:
    """Replace ``target`` with ``data`` atomically and durably.

    The original permission bits are preserved. On any failure the target is
    left untouched and no temp sibling survives.
    """
    directory = target.parent
    tmp = directory / temp_sibling_name(target)
    mode = _current_mode(target)
    # Opened BEFORE the temp file so both descriptors stay live at once: the
    # directory fsync must target its own fd, never a number recycled from
    # the already-closed temp file.
    dir_fd: int | None = None
    with contextlib.suppress(OSError):
        dir_fd = os.open(directory, os.O_RDONLY)
    try:
        try:
            _write_and_sync(tmp, data)
            if mode is not None:
                os.chmod(tmp, mode)
            os.replace(tmp, target)
        finally:
            with contextlib.suppress(OSError):
                tmp.unlink(missing_ok=True)
        if dir_fd is not None:
            _fsync_directory(dir_fd)
    finally:
        if dir_fd is not None:
            os.close(dir_fd)

temp_sibling_name(target)

Return the hidden temp-sibling file name used to stage target.

Pure: the filesystem is never touched. The name is a hidden dotfile carrying the target's own name and the .axmtmp marker, so it can never collide with target.name.

Source code in packages/axm-edit/src/axm_edit/core/atomic_write.py
Python
def temp_sibling_name(target: Path) -> str:
    """Return the hidden temp-sibling file name used to stage ``target``.

    Pure: the filesystem is never touched. The name is a hidden dotfile
    carrying the target's own name and the ``.axmtmp`` marker, so it can never
    collide with ``target.name``.
    """
    return f".{target.name}{_TMP_SUFFIX}"