File size: 939 Bytes
59ebe66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
"""
cache/memo.py — tiny in-memory and file-backed cache
"""

from __future__ import annotations
from pathlib import Path
from typing import Any, Optional
import json
import os

_CACHE: dict[str, Any] = {}
_CACHE_DIR = Path(".cache")
_CACHE_DIR.mkdir(exist_ok=True)

def cache_get(key: str) -> Optional[Any]:
    if key in _CACHE:
        return _CACHE[key]
    f = _CACHE_DIR / (key.replace(":", "_") + ".json")
    if f.exists():
        try:
            with open(f, "r", encoding="utf-8") as fh:
                val = json.load(fh)
            _CACHE[key] = val
            return val
        except Exception:
            return None
    return None

def cache_put(key: str, value: Any) -> None:
    _CACHE[key] = value
    f = _CACHE_DIR / (key.replace(":", "_") + ".json")
    try:
        with open(f, "w", encoding="utf-8") as fh:
            json.dump(value, fh, ensure_ascii=False, indent=2)
    except Exception:
        pass