data_cache¶
Pickled data caching.
This module provides DataCache, a context manager caching a pickled data object - identified by a data id - in the gfs cache folder, so that the computation producing the data can be skipped if a not-too-old cached copy exists.
DataCache
¶
A pickled data object cache.
A DataCache loads - at creation time - the cached data object held in the gfs cache folder, if one exists and is not older than the maximum age. Within the context the data can be replaced via store(): at exit, if the data has been changed, the updated copy is pickled back, so that the next run finds it and skips the computation.
Example
from py_misc_utils import data_cache as dc
with dc.DataCache('daily-stats') as cache:
data = cache.data()
if data is None:
# Missing or too old: recompute and store the new value.
data = {'visits': 42}
cache.store(data)
print(data) # {'visits': 42}
Source code in py_misc_utils/data_cache.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | |
data()
¶
Returns the current data object - the cached one, if any.
Returns:
| Type | Description |
|---|---|
|
The cached data object, or None if no valid cached copy exists. |
Source code in py_misc_utils/data_cache.py
70 71 72 73 74 75 76 | |
store(data)
¶
Stores a new data object, to be pickled at context exit.
The data is written back only if it differs - by identity - from the object loaded at creation time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
The data object to store. |
required |
Example
from py_misc_utils import data_cache as dc
with dc.DataCache('user-prefs') as cache:
cache.store({'theme': 'dark'})
Source code in py_misc_utils/data_cache.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | |