Cache
Pactole Index / Utils / Cache
Auto-generated documentation for utils.cache module.
CacheLoader
Protocol for cache loader functions.
Signature
CacheLoader().call
Load data for the cache.
Signature
CacheTransformer
Protocol for cache transformer functions.
Signature
CacheTransformer().call
Transform the cached data.
Signature
FileCache
A cache that stores data in memory, with a loader function to fetch data from files.
Arguments
file_path (Path | str): The path to the file to cache. file_type (FileType | str, optional): The type of the file (e.g., "csv", "json", "txt"). If not provided, it will be inferred from the file extension. Defaults to None. transformer (CacheTransformer | None, optional): A callable that transforms the cached data. If not provided, it defaults to a function that returns the data unchanged. Defaults to None.
Examples
>>> cache = FileCache("data.csv")
>>> cache.load() # Loads data from data.csv
[{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}]
>>> cache.set([{'name': 'Charlie', 'age': 35}]) # Updates the cache and writes to data.csv
>>> cache.load() # Loads the updated data from data.csv
[{'name': 'Charlie', 'age': 35}]
Signature
class FileCache(MemoryCache):
def __init__(
self,
file_path: Path | str,
file_type: FileType | str | None = None,
transformer: CacheTransformer | None = None,
) -> None: ...
See also
FileCache().date
Get the last modification date of the cache file.
Returns
datetime.datetime- The last modification date of the cache file.
Raises
FileNotFoundError- If the cache file does not exist.
Examples
>>> cache = FileCache("data.csv")
>>> cache.date()
datetime.datetime(2024, 6, 1, 12, 0, 0) # Example modification time
Signature
FileCache().exists
Check if the cache file exists.
Returns
bool- True if the cache file exists, False otherwise.
Examples
Signature
FileCache().path
Get the file path of the cache.
Returns
Path- The file path of the cache.
Examples
Signature
FileCache().size
Get the size of the cache file in bytes.
Returns
int- The size of the cache file in bytes.
Examples
Signature
FileCache().type
Get the file type of the cache.
Returns
FileType- The file type of the cache.
Examples
Signature
MemoryCache
A simple in-memory cache implementation.
Arguments
- Data Any, optional - Initial data to populate the cache. Defaults to None. loader (CacheLoader | None, optional): A callable that loads the data to be cached. If not provided, it defaults to a function that returns None. Defaults to None. transformer (CacheTransformer | None, optional): A callable that transforms the cached data. If not provided, it defaults to a function that returns the data unchanged. Defaults to None.
Examples
>>> class CustomCache(MemoryCache):
... def _read(self):
... return {"data": "value"}
...
>>> cache = CustomCache({"data": "initial"})
>>> cache.data
{'data': 'initial'}
>>> cache.loaded
True
>>> cache.load()
{'data': 'initial'}
>>> cache.load(force=True)
{'data': 'value'}
>>> cache.clear()
>>> cache.data
None
Signature
class MemoryCache:
def __init__(
self,
data: Any = None,
loader: CacheLoader | None = None,
transformer: CacheTransformer | None = None,
) -> None: ...
MemoryCache()._clear
Clear the cache. This method should be overridden.
Signature
MemoryCache()._read
Read the data to be cached. This method should be overridden.
Signature
MemoryCache()._refresh_condition
Determine if the cache should be refreshed. This method should be overridden.
Signature
MemoryCache()._write
Write the data to the cache. This method should be overridden.
Signature
MemoryCache().clear
Clear the cache.
Examples
>>> class CustomCache(MemoryCache):
... def _read(self):
... return {"data": "value"}
...
>>> cache = CustomCache()
>>> cache.load()
{'data': 'value'}
>>> cache.clear()
>>> cache.data
None
Signature
MemoryCache().data
Get the cached data.
Returns
Any- The cached data or None if not loaded.
Examples
>>> cache = MemoryCache()
>>> cache.data
None
>>> cache.set({"key": "value"})
>>> cache.data
{'key': 'value'}
Signature
MemoryCache().load
Load the cached data, refreshing it if necessary.
Arguments
forcebool, optional - If True, forces a refresh of the cache even if it is still valid. Defaults to False.
Returns
Any- The cached data.
Examples
>>> class CustomCache(MemoryCache):
... def _read(self):
... return {"data": "value"}
...
>>> cache = CustomCache()
>>> cache.load()
{'data': 'value'}
Signature
MemoryCache().load_raw
Load the raw data from the loader without applying the transformer.
Note: This method bypasses the cache and always calls the loader directly.
Returns
Any- The raw data without transformation.
Examples
>>> cache = MemoryCache(loader=lambda: {"data": 2}, transformer=lambda x: x * 3)
>>> cache.load_raw()
{'data': 2}
>>> cache.load()
{'data': 6}
Signature
MemoryCache().loaded
Check if the cache has been loaded.
Returns
bool- True if the cache has been loaded, False otherwise.
Examples
>>> class CustomCache(MemoryCache):
... def _read(self):
... return {"data": "value"}
...
>>> cache = CustomCache()
>>> cache.loaded
False
>>> cache.load()
{'data': 'value'}
>>> cache.loaded
True
>>> cache.clear()
>>> cache.loaded
False
>>> cache.set({"data": "new_value"})
>>> cache.loaded
True
Signature
MemoryCache().set
Set the cached data manually.
Arguments
- MemoryCache().data Any - The data to be cached.
Examples
Signature
TimeoutCache
A simple in-memory cache with timeout support.
Arguments
- Data Any, optional - Initial data to populate the cache. Defaults to None. loader (CacheLoader | None, optional): A callable that loads the data to be cached. If not provided, it defaults to a function that returns None. Defaults to None. transformer (CacheTransformer | None, optional): A callable that transforms the cached data. If not provided, it defaults to a function that returns the data unchanged. Defaults to None.
cache_timeoutfloat, optional - The cache timeout in seconds. Defaults to 3600 seconds (1 hour).
Examples
>>> def loader():
... return {"data": "value"}
...
>>> cache = TimeoutCache(loader=loader, cache_timeout=1)
>>> cache.data
None
>>> cache.load()
{'data': 'value'}
>>> cache.data
{'data': 'value'}
>>> cache.expired
False
>>> time.sleep(1.1)
>>> cache.expired
True
>>> cache.load() # This will reload the cache
{'data': 'value'}
>>> cache.clear()
>>> cache.data
None
Signature
class TimeoutCache(MemoryCache):
def __init__(
self,
data: Any = None,
loader: CacheLoader | None = None,
transformer: CacheTransformer | None = None,
cache_timeout: float = DEFAULT_CACHE_TIMEOUT,
) -> None: ...
See also
TimeoutCache().age
Get the age of the cache in seconds.
Returns
float- The age of the cache in seconds.
Examples
>>> def loader():
... return {"data": "value"}
...
>>> cache = TimeoutCache(loader=loader, cache_timeout=10.0)
>>> cache.load()
{'data': 'value'}
>>> age = cache.age
>>> 0 <= age < 0.1
True
Signature
TimeoutCache().expired
Check if the cache has expired.
Returns
bool- True if the cache has expired, False otherwise.
Examples
>>> def loader():
... return {"data": "value"}
...
>>> cache = TimeoutCache(loader=loader, cache_timeout=1)
>>> cache.load()
{'data': 'value'}
>>> cache.expired
False
>>> time.sleep(1.1)
>>> cache.expired
True
Signature
TimeoutCache().timeout
Get the cache timeout in seconds.
Returns
float- The cache timeout in seconds.
Examples
>>> def loader():
... return {"data": "value"}
...
>>> cache = TimeoutCache(loader=loader, cache_timeout=10)
>>> cache.timeout
10.0
Signature
TimeoutCache().timeout
Set the cache timeout in seconds.
Arguments
valuefloat - The new cache timeout in seconds.