Skip to content

API Reference

cachepy.cache_file.cache_file(cache_dir=None, backend='pickle', file_args=None, ignore_args=None, file_pattern=None, env_vars=None, algo='xxhash64', version=None, depends_on_files=None, depends_on_vars=None, verbose=False, hash_file_paths=True)

Disk-backed caching decorator (Python analogue of R's cacheFile).

Returns a :class:CacheDecorator that can be reused across functions::

cf = cache_file("/tmp/cache")

@cf
def step1(x): ...

@cf(verbose=True)
def step2(x): ...

Or used as a one-shot decorator::

@cache_file("/tmp/cache")
def f(x, y=1): ...
Source code in cachepy/cache_file.py
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
def cache_file(
    cache_dir: Optional[os.PathLike | str] = None,
    backend: str = "pickle",
    file_args: Optional[List[str]] = None,
    ignore_args: Optional[List[str]] = None,
    file_pattern: Optional[str] = None,
    env_vars: Optional[List[str]] = None,
    algo: str = "xxhash64",
    version: Optional[str] = None,
    depends_on_files: Optional[List[str]] = None,
    depends_on_vars: Optional[Dict[str, Any]] = None,
    verbose: bool = False,
    hash_file_paths: bool = True,
) -> CacheDecorator:
    """
    Disk-backed caching decorator (Python analogue of R's cacheFile).

    Returns a :class:`CacheDecorator` that can be reused across functions::

        cf = cache_file("/tmp/cache")

        @cf
        def step1(x): ...

        @cf(verbose=True)
        def step2(x): ...

    Or used as a one-shot decorator::

        @cache_file("/tmp/cache")
        def f(x, y=1): ...
    """
    if cache_dir is None:
        cache_dir_path = cache_default_dir()
    else:
        cache_dir_path = Path(cache_dir)

    # attempt to create directory (race-safe)
    try:
        cache_dir_path.mkdir(parents=True, exist_ok=True)
    except Exception:
        logger.warning("cache_file: could not create cache directory %s", cache_dir_path)

    cache_dir_path = cache_dir_path.resolve()
    backend = backend.lower()
    if backend not in {"pickle"}:
        raise ValueError("backend must be 'pickle'")
    ext = "pkl"

    # static path specs from function body (stubbed for now)
    path_specs = _find_path_specs  # function; we will call inside decorator

    def decorator(f: Callable) -> Callable:
        sig = inspect.signature(f)
        ps = path_specs(f)
        static_dirs_lit: List[str] = ps.get("literals", [])
        static_dirs_sym: List[str] = ps.get("symbols", [])
        # Detect import names at decoration time (AST is static)
        _import_names = _detect_import_names(f)

        def _get_path_hash(path: os.PathLike | str) -> str:
            p = Path(path).resolve()
            if p.is_dir():
                # list files recursively, optional regex filter
                files = []
                for sub in sorted(p.rglob("*")):
                    if sub.is_file():
                        if file_pattern is not None:
                            if not re.search(file_pattern, sub.name):
                                continue
                        files.append(sub)
                if not files:
                    return "empty_dir"
                # hash (relative name, content hash) for structure + content
                file_entries = []
                for sub in files:
                    rel = str(sub.relative_to(p))
                    file_entries.append((rel, fast_file_hash(sub, algo=algo)))
                return _digest_obj(file_entries, algo=algo)
            elif p.is_file():
                return fast_file_hash(p, algo=algo)
            else:
                return ""

        def _atomic_save(obj: Any, path: Path) -> None:
            """
            Atomic write:
              - write to temp file in same dir
              - os.replace() to target
            """
            path = Path(path)
            tmp_name = f"{path.name}.tmp.{''.join(random.choices('abcdefghijklmnopqrstuvwxyz0123456789', k=8))}"
            tmp_path = path.with_name(tmp_name)

            try:
                with tmp_path.open("wb") as f2:
                    pickle.dump(obj, f2, protocol=pickle.HIGHEST_PROTOCOL)

                try:
                    os.replace(tmp_path, path)
                except OSError:
                    # fallback: copy+unlink
                    import shutil

                    shutil.copy2(tmp_path, path)
                    tmp_path.unlink(missing_ok=True)

                # best-effort permissions (like 0664)
                if os.name == "posix":
                    try:
                        os.chmod(path, 0o664)
                    except OSError:
                        pass
            except Exception as e:
                logger.warning("cache_file: failed to save cache file %s: %s", path, e)
                try:
                    tmp_path.unlink(missing_ok=True)
                except Exception:
                    pass

        def _safe_load(path: Path) -> Any:
            with path.open("rb") as f2:
                obj = pickle.load(f2)
            # expect {"dat": value, "meta": {...}}
            if isinstance(obj, dict) and "dat" in obj:
                return obj["dat"]
            return obj

        def _safe_load_full(path: Path) -> Optional[Dict[str, Any]]:
            """Load a cache file and return the raw dict (with 'dat' and 'meta')."""
            try:
                with path.open("rb") as f2:
                    obj = pickle.load(f2)
                if isinstance(obj, dict) and "meta" in obj:
                    return obj
            except Exception:
                pass
            return None

        def wrapper(*args, _load: bool = True, _force: bool = False, _skip_save: bool = False, **kwargs):
            invoke_env_globals = f.__globals__

            # -------- function name for filename label --------
            fname = getattr(f, "__name__", "anon")

            # -------- normalize arguments (include defaults) --------
            bound = sig.bind_partial(*args, **kwargs)
            bound.apply_defaults()

            args_for_hash: Dict[str, Any] = dict(bound.arguments)
            # remove control params from hashing
            args_for_hash.pop("_load", None)
            args_for_hash.pop("_force", None)
            args_for_hash.pop("_skip_save", None)

            if ignore_args:
                for nm in ignore_args:
                    args_for_hash.pop(nm, None)

            # order by argument name for stability
            args_for_hash = dict(sorted(args_for_hash.items(), key=lambda kv: kv[0]))

            # Sort **kwargs dict values for order-independent hashing
            for param_name, param in sig.parameters.items():
                if param.kind == inspect.Parameter.VAR_KEYWORD and param_name in args_for_hash:
                    val = args_for_hash[param_name]
                    if isinstance(val, dict):
                        args_for_hash[param_name] = dict(sorted(val.items(), key=lambda kv: kv[0]))

            # -------- resolve symlinks and normalize file_args --------
            if file_args:
                for nm in file_args:
                    if nm in args_for_hash:
                        val = args_for_hash[nm]
                        if isinstance(val, (str, Path)):
                            resolved = str(Path(val).resolve())
                            if not hash_file_paths and Path(resolved).exists():
                                args_for_hash[nm] = _get_path_hash(resolved)
                            else:
                                args_for_hash[nm] = resolved

            # -------- dynamic path scanning over arguments --------
            def _collect_paths(val: Any) -> List[Path]:
                """Recursively extract file/directory paths from any value."""
                out: List[Path] = []
                if isinstance(val, Path):
                    out.append(val)
                elif isinstance(val, str):
                    # only treat as path if it looks like one
                    if os.sep in val or val.startswith(".") or val.startswith("~"):
                        out.append(Path(val))
                elif isinstance(val, dict):
                    for v in val.values():
                        out.extend(_collect_paths(v))
                elif isinstance(val, (list, tuple, set)):
                    for v in val:
                        out.extend(_collect_paths(v))
                return out

            dir_hashes_args: Dict[str, str] = {}

            if args_for_hash:
                if file_args:
                    scan_items = {k: v for k, v in args_for_hash.items() if k in file_args}
                else:
                    scan_items = args_for_hash

                for nm, expr_val in scan_items.items():
                    paths = _collect_paths(expr_val)
                    if not paths:
                        continue
                    for p in paths:
                        if p.exists():
                            h = _get_path_hash(p)
                            dir_hashes_args[str(p.resolve())] = h

            # -------- static path scanning (currently just stubbed lists) --------
            # literals
            static_hashes_lit: Dict[str, str] = {}
            for lit in static_dirs_lit:
                h = _get_path_hash(lit)
                static_hashes_lit[lit] = h

            # symbols: look up in globals and hash underlying paths
            static_hashes_sym: Dict[str, str] = {}
            for sym in static_dirs_sym:
                val = invoke_env_globals.get(sym)
                if isinstance(val, (str, Path, list, tuple)):
                    paths = _collect_paths(val)
                    sub_hashes = {str(Path(p).resolve()): _get_path_hash(p) for p in paths}
                    static_hashes_sym[f"sym:{sym}"] = _digest_obj(sub_hashes, algo=algo)

            # -------- environment variables --------
            current_envs: Optional[Dict[str, Optional[str]]] = None
            if env_vars:
                vars_sorted = sorted(env_vars)
                current_envs = {name: os.getenv(name) for name in vars_sorted}

            # -------- recursive closure hash --------
            deep_hash = get_recursive_closure_hash(f, algo=algo)

            # -------- package version detection --------
            pkg_versions = _get_package_versions(_import_names, f)

            # -------- build master hash --------
            dir_states: Dict[str, str] = {}
            dir_states.update(dir_hashes_args)
            dir_states.update(static_hashes_lit)
            dir_states.update(static_hashes_sym)

            # -------- depends_on_files hashing --------
            dep_file_hashes = None
            if depends_on_files:
                dep_file_hashes = {p: _get_path_hash(p) for p in sorted(depends_on_files)}

            hashlist = {
                "call": args_for_hash,
                "closure": deep_hash,
                "dir_states": dict(sorted(dir_states.items(), key=lambda kv: kv[0])),
                "envs": current_envs,
                "version": version,
                "depends_on_files": dep_file_hashes,
                "depends_on_vars": depends_on_vars,
                "pkgs": pkg_versions,
            }

            args_hash = _digest_obj(hashlist, algo=algo)
            outfile = cache_dir_path / f"{fname}.{args_hash}.{ext}"

            # -------- register node in cache tree --------
            node_id = f"{fname}:{args_hash}"
            _cache_tree_register_node(node_id, fname, args_hash, outfile)

            _cache_tree_call_stack.append(node_id)
            try:
                # 1. optimistic load
                sentinel_path = outfile.with_suffix(outfile.suffix + ".computing")
                if _load and not _force and outfile.exists():
                    try:
                        result = _safe_load(outfile)
                        if verbose:
                            logger.info("[%s] cache hit", fname)
                        return result
                    except Exception:
                        # partial/corrupt -> ignore and recompute
                        pass

                # 1b. check if another process is already computing
                if not _force:
                    waited_result = _wait_for_sentinel(
                        sentinel_path, outfile, _safe_load, fname
                    )
                    if waited_result is not None:
                        return waited_result

                # verbose: report why we're computing
                if verbose:
                    if _force:
                        logger.info("[%s] forced re-execution", fname)
                    else:
                        existing = sorted(
                            cache_dir_path.glob(f"{fname}.*.{ext}"),
                            key=lambda p: p.stat().st_mtime,
                        )
                        if not existing:
                            logger.info("[%s] first execution", fname)
                        else:
                            stored = _safe_load_full(existing[-1])
                            if stored is not None:
                                sm = stored["meta"]
                                _MISS_LABELS = {
                                    "call": "arguments",
                                    "closure": "function body/closure",
                                    "dir_states": "file/directory contents",
                                    "envs": "environment variables",
                                    "version": "version",
                                    "depends_on_files": "explicit file dependencies",
                                    "depends_on_vars": "explicit variable dependencies",
                                    "pkgs": "package versions",
                                }
                                changes = [
                                    label for key, label in _MISS_LABELS.items()
                                    if sm.get(key) != hashlist.get(key)
                                ]
                                if not changes:
                                    changes = ["unknown (possibly new argument combination)"]
                                logger.info("[%s] cache miss -- changed: %s", fname, ", ".join(changes))
                            else:
                                logger.info("[%s] cache miss (previous entry unreadable)", fname)

                # 2. record pre-execution file hashes for modification warning
                pre_file_hashes: Dict[str, str] = {}
                if file_args and dir_hashes_args:
                    pre_file_hashes = dict(dir_hashes_args)

                # 3. compute with sentinel
                try:
                    sentinel_path.touch()
                except OSError:
                    pass

                try:
                    dat = f(*args, **kwargs)
                except Exception:
                    # Remove graph node on error
                    _cache_tree_graph.pop(node_id, None)
                    raise
                finally:
                    # Always clean up sentinel
                    try:
                        sentinel_path.unlink(missing_ok=True)
                    except OSError:
                        pass

                # 4. check for file modification during execution
                if pre_file_hashes:
                    import warnings as _warnings
                    _file_state_cache.clear()  # force re-hash
                    for pstr, old_h in pre_file_hashes.items():
                        p = Path(pstr)
                        if p.exists():
                            new_h = _get_path_hash(p)
                            if new_h != old_h:
                                _warnings.warn(
                                    f"File modified during execution: {pstr}",
                                    stacklevel=2,
                                )

                if not _skip_save:
                    save_data = {"dat": dat, "meta": hashlist}

                    # 3. try file locking if available
                    lock = None
                    lock_path = outfile.with_suffix(outfile.suffix + ".lock")
                    try:
                        from filelock import FileLock  # type: ignore

                        lock = FileLock(str(lock_path))
                        lock.acquire(timeout=5)
                    except Exception:
                        lock = None

                    try:
                        # double-check: maybe someone else wrote it while we computed
                        if _load and not _force and outfile.exists():
                            try:
                                return _safe_load(outfile)
                            except Exception:
                                pass
                        _atomic_save(save_data, outfile)
                    finally:
                        if lock is not None:
                            try:
                                lock.release()
                            except Exception:
                                pass

                return dat
            finally:
                _cache_tree_call_stack.pop()

        # preserve metadata
        wrapper.__name__ = getattr(f, "__name__", "cached_fn")
        wrapper.__doc__ = f.__doc__
        wrapper.__wrapped__ = f  # for inspect
        return wrapper

    defaults = dict(
        cache_dir=cache_dir, backend=backend, file_args=file_args,
        ignore_args=ignore_args, file_pattern=file_pattern,
        env_vars=env_vars, algo=algo, version=version,
        depends_on_files=depends_on_files, depends_on_vars=depends_on_vars,
        verbose=verbose, hash_file_paths=hash_file_paths,
    )
    return CacheDecorator(decorator, **defaults)

cachepy.cache_file.track_file(path)

Record that the current cached node depends on this file path. Returns a normalized Path to allow convenient usage inside user code.

Source code in cachepy/cache_file.py
def track_file(path: os.PathLike | str) -> Path:
    """
    Record that the current cached node depends on this file path.
    Returns a normalized Path to allow convenient usage inside user code.
    """
    node_id = _cache_tree_current_node()
    if node_id is None:
        return Path(path)

    node = _cache_tree_graph.get(node_id)
    if node is None:
        return Path(path)

    np = Path(path).resolve()

    files: List[Path] = node.get("files", [])
    if np not in files:
        files.append(np)
        node["files"] = files

    fh: Dict[str, Optional[str]] = node.get("file_hashes", {})
    if np.exists():
        fh[str(np)] = fast_file_hash(np)
    else:
        fh[str(np)] = None

    node["file_hashes"] = fh
    _cache_tree_graph[node_id] = node
    return np

cachepy.cache_file.cache_tree_nodes()

Return a copy of all nodes currently recorded in the cache tree.

Source code in cachepy/cache_file.py
def cache_tree_nodes() -> Dict[str, Dict[str, Any]]:
    """Return a copy of all nodes currently recorded in the cache tree."""
    # Shallow copy is enough to avoid accidental mutation of dict itself
    return dict(_cache_tree_graph)

cachepy.cache_file.cache_tree_reset()

Reset the in-memory cache tree graph + call stack.

Source code in cachepy/cache_file.py
def cache_tree_reset() -> None:
    """Reset the in-memory cache tree graph + call stack."""
    _cache_tree_call_stack.clear()
    _cache_tree_graph.clear()

cachepy.cache_file.cache_tree_save(path)

Save a serializable representation (named dict of nodes) to disk.

Source code in cachepy/cache_file.py
def cache_tree_save(path: os.PathLike | str) -> Path:
    """Save a serializable representation (named dict of nodes) to disk."""
    path = Path(path)
    with path.open("wb") as f:
        pickle.dump(cache_tree_nodes(), f)
    return path

cachepy.cache_file.cache_tree_load(path)

Load a cache tree representation saved by cache_tree_save.

Source code in cachepy/cache_file.py
def cache_tree_load(path: os.PathLike | str) -> None:
    """Load a cache tree representation saved by cache_tree_save."""
    path = Path(path)
    with path.open("rb") as f:
        graph_dict = pickle.load(f)

    _cache_tree_graph.clear()
    _cache_tree_graph.update(graph_dict)
    _cache_tree_call_stack.clear()

cachepy.cache_file.cache_tree_changed_files()

For each node, check whether any tracked files changed or disappeared. Returns dict[node_id] = {"node": node, "changed_files": [Path, ...]}

Source code in cachepy/cache_file.py
def cache_tree_changed_files() -> Dict[str, Dict[str, Any]]:
    """
    For each node, check whether any tracked files changed or disappeared.
    Returns dict[node_id] = {"node": node, "changed_files": [Path, ...]}
    """
    out: Dict[str, Dict[str, Any]] = {}

    for node_id, node in _cache_tree_graph.items():
        fh: Dict[str, Optional[str]] = node.get("file_hashes", {})
        if not fh:
            continue

        changed_paths: List[Path] = []

        for p_str, old_hash in fh.items():
            p = Path(p_str)
            if not p.exists():
                changed_paths.append(p)
            else:
                new_hash = fast_file_hash(p)
                if old_hash != new_hash:
                    changed_paths.append(p)

        if changed_paths:
            out[node_id] = {
                "node": node,
                "changed_files": changed_paths,
            }

    return out

cachepy.cache_file.cache_stats(cache_dir)

Return aggregate statistics for a cache directory. Excludes graph.pkl from counts.

Source code in cachepy/cache_file.py
def cache_stats(cache_dir: os.PathLike | str) -> Dict[str, Any]:
    """
    Return aggregate statistics for a cache directory.
    Excludes graph.pkl from counts.
    """
    cache_dir = Path(cache_dir)
    if not cache_dir.exists():
        raise FileNotFoundError(f"Cache directory not found: {cache_dir}")

    files = [
        p for p in cache_dir.iterdir()
        if p.is_file()
        and p.name.endswith(".pkl")
        and not p.name.startswith("graph.")
    ]

    if not files:
        return {
            "n_entries": 0,
            "total_size_mb": 0.0,
            "oldest": None,
            "newest": None,
        }

    sizes = [p.stat().st_size for p in files]
    mtimes = [p.stat().st_mtime for p in files]

    # per-function breakdown: extract fname from filename pattern "fname.hash.ext"
    by_func: Dict[str, Dict[str, Any]] = {}
    for p, sz in zip(files, sizes):
        parts = p.stem.rsplit(".", 1)  # "fname.hash" -> ["fname", "hash"]
        fn = parts[0] if len(parts) == 2 else p.stem
        if fn not in by_func:
            by_func[fn] = {"fname": fn, "n_files": 0, "total_size_mb": 0.0}
        by_func[fn]["n_files"] += 1
        by_func[fn]["total_size_mb"] += sz / (1024 * 1024)

    return {
        "n_entries": len(files),
        "total_size_mb": sum(sizes) / (1024 * 1024),
        "oldest": min(mtimes),
        "newest": max(mtimes),
        "by_function": sorted(by_func.values(), key=lambda d: d["fname"]),
    }

cachepy.cache_file.cache_prune(cache_dir, days_old=30)

Delete cache files older than days_old, based on mtime. Also cleans up .lock, .tmp.*, and .computing files unconditionally.

Source code in cachepy/cache_file.py
def cache_prune(cache_dir: os.PathLike | str, days_old: int = 30) -> None:
    """
    Delete cache files older than days_old, based on mtime.
    Also cleans up .lock, .tmp.*, and .computing files unconditionally.
    """
    cache_dir = Path(cache_dir)
    if not cache_dir.exists():
        return

    cutoff_sec = time.time() - days_old * 24 * 3600
    to_delete: List[Path] = []

    for p in cache_dir.glob("*.pkl"):
        if p.stat().st_mtime < cutoff_sec:
            to_delete.append(p)

    # Always clean up stale auxiliary files
    for p in cache_dir.glob("*.lock"):
        to_delete.append(p)
    for p in cache_dir.glob("*.tmp.*"):
        to_delete.append(p)
    for p in cache_dir.glob("*.computing"):
        to_delete.append(p)

    if to_delete:
        logger.info("Deleting %d old/stale cache files...", len(to_delete))
        for p in to_delete:
            try:
                p.unlink()
            except OSError:
                logger.warning("Failed to delete %s", p)

cachepy.cache_file.load_config(path, existing=None)

Load cachepy configuration from a YAML file. If existing is provided, keys already in existing are NOT overridden.

Source code in cachepy/cache_file.py
def load_config(
    path: os.PathLike | str,
    existing: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """
    Load cachepy configuration from a YAML file.
    If *existing* is provided, keys already in existing are NOT overridden.
    """
    import yaml

    path = Path(path)
    with path.open() as f:
        data = yaml.safe_load(f) or {}

    if existing is not None:
        merged = dict(data)
        merged.update(existing)  # existing wins
        return merged

    return data