Skip to content

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
class 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}
  """

  def __init__(self, data_id, max_age=_MAX_AGE):
    """Creates a data cache.

    Args:
      data_id: The id uniquely identifying the cached data.
      max_age: The maximum age - in seconds - of the cached data to be
        considered valid. If None, the cached data never expires.
    """
    fsid = hashlib.sha1(data_id.encode()).hexdigest()

    cache_path = os.path.join(gfs.cache_dir(), 'data_cache')
    gfs.makedirs(cache_path, exist_ok=True)

    self._data_path = os.path.join(cache_path, fsid)
    self._orig_data = None
    try:
      sres = gfs.stat(self._data_path)
      if max_age is None or (sres.st_ctime + max_age) > time.time():
        with gfs.open(self._data_path, mode='rb') as fd:
          self._orig_data = pickle.load(fd)
    # Pickle payloads can raise nearly anything when stale/corrupt: treat
    # every load failure as a cache miss - the source data is the fallback.
    except:  # noqa: E722, S110
      pass

    self._data = self._orig_data

  def data(self):
    """Returns the current data object - the cached one, if any.

    Returns:
      The cached data object, or None if no valid cached copy exists.
    """
    return self._data

  def store(self, 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.

    Args:
      data: The data object to store.

    Example:
      from py_misc_utils import data_cache as dc

      with dc.DataCache('user-prefs') as cache:
        cache.store({'theme': 'dark'})
    """
    self._data = data

  def __enter__(self):
    """Enters the data cache context."""

    return self

  def __exit__(self, *exc):
    """Exits the data cache context, pickling back changed data."""
    if self._data is not None and self._data is not self._orig_data:
      with gfs.open(self._data_path, mode='wb') as fd:
        pickle.dump(self._data, fd)

    return False

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
def data(self):
  """Returns the current data object - the cached one, if any.

  Returns:
    The cached data object, or None if no valid cached copy exists.
  """
  return self._data

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
def store(self, 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.

  Args:
    data: The data object to store.

  Example:
    from py_misc_utils import data_cache as dc

    with dc.DataCache('user-prefs') as cache:
      cache.store({'theme': 'dark'})
  """
  self._data = data