Skip to content

temporary

temporary #

A throwaway scratch scoped to a with block: active inside, deleted on exit.

temporary(path=None, *, max_size_gb=None) #

Open a throwaway scratch, active for the block and deleted on exit.

The scratch is active in the calling thread or task only: other threads keep the default, so a dry run in a worker never redirects live callers.

Parameters:

Name Type Description Default
path str | Path | None

Where to root the scratch. A fresh temp directory when omitted.

None
max_size_gb float | None

Hard cap on the cache's byte budget, in gigabytes.

None

Yields:

Type Description
Scratch

The temporary scratch handle (also installed as the active one).

Source code in capturegraph-lib/capturegraph/recipes/scratch/temporary.py
@contextmanager
def temporary(
    path: str | Path | None = None,
    *,
    max_size_gb: float | None = None,
) -> Iterator[Scratch]:
    """Open a throwaway scratch, active for the block and deleted on exit.

    The scratch is active in the calling thread or task only: other threads keep
    the default, so a dry run in a worker never redirects live callers.

    Args:
        path: Where to root the scratch. A fresh temp directory when omitted.
        max_size_gb: Hard cap on the cache's byte budget, in gigabytes.

    Yields:
        The temporary scratch handle (also installed as the active one).
    """
    if path is not None:
        delete_target = root = Path(path)
    else:
        delete_target = Path(tempfile.mkdtemp(prefix="cg-scratch-"))
        root = delete_target / ".cg-scratch"
    scratch = Scratch(root, max_size_gb=max_size_gb)
    token = scoped_scratch.set(scratch)
    try:
        yield scratch
    finally:
        scoped_scratch.reset(token)
        scratch.close()
        shutil.rmtree(delete_target, ignore_errors=True)