Skip to content

Cache API Reference

In-memory TTL caching with decorator support.

financelib.cache.MemoryCache(default_ttl: int = 300, max_size: int = 1000)

Bases: BaseCacheBackend

Thread-safe in-memory cache with TTL support.

Parameters:

Name Type Description Default
default_ttl int

Default TTL in seconds (0 = no expiration).

300
max_size int

Maximum number of entries (0 = unlimited).

1000
Example

cache = MemoryCache(default_ttl=300) cache.set("price:THYAO", 172.45) cache.get("price:THYAO") 172.45

Source code in financelib/cache.py
def __init__(self, default_ttl: int = 300, max_size: int = 1000) -> None:
    self.default_ttl = default_ttl
    self.max_size = max_size
    self._store: dict[str, tuple[Any, float]] = {}  # key → (value, expiry_time)
    self._lock = threading.Lock()

Functions

clear() -> None

Clear all cached entries.

Source code in financelib/cache.py
def clear(self) -> None:
    """Clear all cached entries."""
    with self._lock:
        self._store.clear()

delete(key: str) -> bool

Delete a key.

Parameters:

Name Type Description Default
key str

Cache key.

required

Returns:

Type Description
bool

True if the key existed.

Source code in financelib/cache.py
def delete(self, key: str) -> bool:
    """Delete a key.

    Args:
        key: Cache key.

    Returns:
        True if the key existed.
    """
    with self._lock:
        if key in self._store:
            del self._store[key]
            return True
        return False

get(key: str) -> Optional[Any]

Get a value by key.

Returns None if the key doesn't exist or has expired.

Parameters:

Name Type Description Default
key str

Cache key.

required

Returns:

Type Description
Optional[Any]

Cached value or None.

Source code in financelib/cache.py
def get(self, key: str) -> Optional[Any]:
    """Get a value by key.

    Returns None if the key doesn't exist or has expired.

    Args:
        key: Cache key.

    Returns:
        Cached value or None.
    """
    with self._lock:
        if key not in self._store:
            return None
        value, expiry = self._store[key]
        if expiry > 0 and time.time() > expiry:
            del self._store[key]
            return None
        return value

set(key: str, value: Any, ttl: Optional[int] = None) -> None

Set a value with optional TTL.

Parameters:

Name Type Description Default
key str

Cache key.

required
value Any

Value to cache.

required
ttl Optional[int]

TTL in seconds. Uses default_ttl if None.

None
Source code in financelib/cache.py
def set(self, key: str, value: Any, ttl: Optional[int] = None) -> None:
    """Set a value with optional TTL.

    Args:
        key: Cache key.
        value: Value to cache.
        ttl: TTL in seconds. Uses default_ttl if None.
    """
    effective_ttl = ttl if ttl is not None else self.default_ttl
    expiry = time.time() + effective_ttl if effective_ttl > 0 else 0

    with self._lock:
        if self.max_size > 0 and len(self._store) >= self.max_size and key not in self._store:
            self._evict_expired()
            if len(self._store) >= self.max_size:
                # Remove oldest entry
                oldest_key = next(iter(self._store))
                del self._store[oldest_key]
        self._store[key] = (value, expiry)

size() -> int

Get the number of cached entries (including expired).

Source code in financelib/cache.py
def size(self) -> int:
    """Get the number of cached entries (including expired)."""
    return len(self._store)

financelib.cache.cached(ttl: int = 300, cache: Optional[BaseCacheBackend] = None) -> Callable[[F], F]

Decorator to cache function results.

Parameters:

Name Type Description Default
ttl int

Cache TTL in seconds.

300
cache Optional[BaseCacheBackend]

Cache backend to use. Uses global MemoryCache if None.

None

Returns:

Type Description
Callable[[F], F]

Decorated function.

Example

@cached(ttl=60) ... def fetch_price(symbol): ... return api.get_price(symbol)

Source code in financelib/cache.py
def cached(ttl: int = 300, cache: Optional[BaseCacheBackend] = None) -> Callable[[F], F]:
    """Decorator to cache function results.

    Args:
        ttl: Cache TTL in seconds.
        cache: Cache backend to use. Uses global MemoryCache if None.

    Returns:
        Decorated function.

    Example:
        >>> @cached(ttl=60)
        ... def fetch_price(symbol):
        ...     return api.get_price(symbol)
    """
    def decorator(func: F) -> F:
        _cache = cache or _default_cache

        @functools.wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            key = _make_cache_key(func, args, kwargs)
            result = _cache.get(key)
            if result is not None:
                return result
            result = func(*args, **kwargs)
            if result is not None:
                _cache.set(key, result, ttl)
            return result

        wrapper.cache_clear = lambda: _cache.clear()  # type: ignore[attr-defined]
        return wrapper  # type: ignore[return-value]
    return decorator

financelib.cache.get_default_cache() -> MemoryCache

Get the global default cache instance.

Source code in financelib/cache.py
def get_default_cache() -> MemoryCache:
    """Get the global default cache instance."""
    return _default_cache