"""
Memory-based cache implementation for the countryflag package.
This module contains the MemoryCache class, which implements in-memory caching.
"""
import threading
from typing import Any, Dict, Optional
from countryflag.cache.base import Cache
[docs]
class MemoryCache(Cache):
"""
In-memory cache implementation.
This class implements a simple in-memory cache using a dictionary.
Attributes:
_cache: Dictionary that stores the cached values.
"""
[docs]
def __init__(self) -> None:
"""
Initialize the memory cache.
"""
self._cache: Dict[str, Any] = {}
self._hits = 0 # Initialize hit counter
self._lock = threading.RLock() # Add a lock
[docs]
def get(self, key: str) -> Optional[Any]:
"""
Get a value from the cache.
Args:
key: The cache key.
Returns:
The cached value, or None if the key is not in the cache.
Example:
>>> cache = MemoryCache()
>>> cache.set("key", "value")
>>> cache.get("key")
'value'
>>> cache.get("nonexistent")
None
"""
with self._lock:
value = self._cache.get(key)
if value is not None:
self._hits += 1 # Increment hit counter
return value
[docs]
def set(self, key: str, value: Any) -> None:
"""
Set a value in the cache.
Args:
key: The cache key.
value: The value to cache.
Example:
>>> cache = MemoryCache()
>>> cache.set("key", "value")
>>> cache.get("key")
'value'
"""
with self._lock:
self._cache[key] = value
[docs]
def delete(self, key: str) -> None:
"""
Delete a value from the cache.
Args:
key: The cache key to delete.
Example:
>>> cache = MemoryCache()
>>> cache.set("key", "value")
>>> cache.delete("key")
>>> cache.get("key")
None
"""
with self._lock:
if key in self._cache:
del self._cache[key]
[docs]
def clear(self) -> None:
"""
Clear all values from the cache.
Example:
>>> cache = MemoryCache()
>>> cache.set("key1", "value1")
>>> cache.set("key2", "value2")
>>> cache.clear()
>>> cache.get("key1")
None
>>> cache.get("key2")
None
"""
with self._lock:
self._cache.clear()
[docs]
def contains(self, key: str) -> bool:
"""
Check if a key exists in the cache.
Args:
key: The cache key to check.
Returns:
bool: True if the key exists in the cache, False otherwise.
Example:
>>> cache = MemoryCache()
>>> cache.set("key", "value")
>>> cache.contains("key")
True
>>> cache.contains("nonexistent")
False
"""
with self._lock:
return key in self._cache
[docs]
def get_hits(self) -> int:
"""
Get the number of cache hits.
Returns:
int: The number of cache hits.
"""
with self._lock:
return self._hits
@property
def hits(self) -> int:
"""
Property to get the number of cache hits.
Returns:
int: The number of cache hits.
"""
return self.get_hits()
[docs]
def reset_hits(self) -> None:
"""
Reset the cache hit counter.
"""
with self._lock:
self._hits = 0