Skip to content

object_cache

Object cache with TTL-based eviction and automatic cleanup.

This module provides: - Cache: Thread-safe object pool with time-based expiration - Handler: Abstract base class for custom object lifecycle management - cache(): Global singleton cache instance

Objects are automatically returned to the cache when the FinWrapper is closed or garbage collected.

Example
import gc

import py_misc_utils.object_cache as oc


class Conn:

  def query(self, q):
    return f'result:{q}'


class ConnHandler(oc.Handler):

  def __init__(self):
    self.created = 0

  def create(self):
    self.created += 1
    return Conn()


cache = oc.Cache(clean_timeo=60)
handler = ConnHandler()

conn = cache.get('db1', handler)
assert conn.query('SELECT 1') == 'result:SELECT 1'
assert handler.created == 1

del conn  # The FinWrapper finalizer returns the object to the pool.
gc.collect()
conn = cache.get('db1', handler)
assert handler.created == 1  # Reused - no new object created.
cache.shutdown()

Handler

Bases: ABC

Abstract base class for defining object lifecycle in the cache.

Subclasses implement create(), and optionally max_age(), is_alive(), and close() for custom behavior.

Source code in py_misc_utils/object_cache.py
 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
class Handler(abc.ABC):
  """Abstract base class for defining object lifecycle in the cache.

  Subclasses implement create(), and optionally max_age(), is_alive(),
  and close() for custom behavior.
  """

  @abc.abstractmethod
  def create(self):
    """Create a new object instance.

    Called when no suitable cached object is available.

    Returns:
      A new object instance.
    """
    ...

  def max_age(self):
    """Maximum age of cached objects in seconds before eviction.

    Returns:
      Maximum age in seconds (default: 60).
    """
    return 60

  def is_alive(self, obj):
    """Check if a cached object is still valid.

    Called when retrieving an object from the cache.

    Args:
      obj: Cached object to check.

    Returns:
      True if object is valid, False if it should be discarded.

    Example:
      import gc

      import py_misc_utils.object_cache as oc


      class Handler(oc.Handler):

        def __init__(self):
          self.created = 0
          self.alive = True

        def create(self):
          self.created += 1
          return object()

        def is_alive(self, obj):
          return self.alive


      cache = oc.Cache(clean_timeo=60)
      handler = Handler()
      obj = cache.get('k', handler)
      del obj
      gc.collect()
      handler.alive = False
      obj = cache.get('k', handler)
      assert handler.created == 2  # Dead object discarded, a new one created.
      cache.shutdown()
    """
    return True

  def close(self, obj):
    """Clean up an object when evicted or discarded.

    Args:
      obj: Object to clean up.
    """

create() abstractmethod

Create a new object instance.

Called when no suitable cached object is available.

Returns:

Type Description

A new object instance.

Source code in py_misc_utils/object_cache.py
68
69
70
71
72
73
74
75
76
77
@abc.abstractmethod
def create(self):
  """Create a new object instance.

  Called when no suitable cached object is available.

  Returns:
    A new object instance.
  """
  ...

max_age()

Maximum age of cached objects in seconds before eviction.

Returns:

Type Description

Maximum age in seconds (default: 60).

Source code in py_misc_utils/object_cache.py
79
80
81
82
83
84
85
def max_age(self):
  """Maximum age of cached objects in seconds before eviction.

  Returns:
    Maximum age in seconds (default: 60).
  """
  return 60

is_alive(obj)

Check if a cached object is still valid.

Called when retrieving an object from the cache.

Parameters:

Name Type Description Default
obj

Cached object to check.

required

Returns:

Type Description

True if object is valid, False if it should be discarded.

Example
import gc

import py_misc_utils.object_cache as oc


class Handler(oc.Handler):

  def __init__(self):
    self.created = 0
    self.alive = True

  def create(self):
    self.created += 1
    return object()

  def is_alive(self, obj):
    return self.alive


cache = oc.Cache(clean_timeo=60)
handler = Handler()
obj = cache.get('k', handler)
del obj
gc.collect()
handler.alive = False
obj = cache.get('k', handler)
assert handler.created == 2  # Dead object discarded, a new one created.
cache.shutdown()
Source code in py_misc_utils/object_cache.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def is_alive(self, obj):
  """Check if a cached object is still valid.

  Called when retrieving an object from the cache.

  Args:
    obj: Cached object to check.

  Returns:
    True if object is valid, False if it should be discarded.

  Example:
    import gc

    import py_misc_utils.object_cache as oc


    class Handler(oc.Handler):

      def __init__(self):
        self.created = 0
        self.alive = True

      def create(self):
        self.created += 1
        return object()

      def is_alive(self, obj):
        return self.alive


    cache = oc.Cache(clean_timeo=60)
    handler = Handler()
    obj = cache.get('k', handler)
    del obj
    gc.collect()
    handler.alive = False
    obj = cache.get('k', handler)
    assert handler.created == 2  # Dead object discarded, a new one created.
    cache.shutdown()
  """
  return True

close(obj)

Clean up an object when evicted or discarded.

Parameters:

Name Type Description Default
obj

Object to clean up.

required
Source code in py_misc_utils/object_cache.py
130
131
132
133
134
135
def close(self, obj):
  """Clean up an object when evicted or discarded.

  Args:
    obj: Object to clean up.
  """

Cache

Thread-safe object cache with TTL-based eviction.

Maintains pools of objects by name, with a background cleaner that periodically removes expired objects.

Example
import gc

import py_misc_utils.object_cache as oc


class Handler(oc.Handler):

  def __init__(self):
    self.created = 0

  def create(self):
    self.created += 1
    return object()


cache = oc.Cache(clean_timeo=60)
handler = Handler()

obj = cache.get('key1', handler)
assert handler.created == 1
del obj
gc.collect()
obj = cache.get('key1', handler)
assert handler.created == 1  # Pooled object reused.
cache.shutdown()
Source code in py_misc_utils/object_cache.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
class Cache:
  """Thread-safe object cache with TTL-based eviction.

  Maintains pools of objects by name, with a background cleaner that
  periodically removes expired objects.

  Example:
    import gc

    import py_misc_utils.object_cache as oc


    class Handler(oc.Handler):

      def __init__(self):
        self.created = 0

      def create(self):
        self.created += 1
        return object()


    cache = oc.Cache(clean_timeo=60)
    handler = Handler()

    obj = cache.get('key1', handler)
    assert handler.created == 1
    del obj
    gc.collect()
    obj = cache.get('key1', handler)
    assert handler.created == 1  # Pooled object reused.
    cache.shutdown()
  """

  def __init__(self, clean_timeo=None):
    """Initialize the cache.

    Args:
      clean_timeo: Cleanup interval in seconds (default: from
        CACHE_CLEAN_TIMEO env var or 8).
    """
    self._lock = threading.Lock()
    self._cond = threading.Condition(lock=self._lock)
    self._cache = collections.defaultdict(collections.deque)
    self._cleaner = ptsk.PeriodicTask(
        'CacheCleaner',
        self._try_cleanup,
        clean_timeo or int(os.getenv('CACHE_CLEAN_TIMEO', '8')),
        stop_on_error=False,
    )
    self._cleaner.start()

  def _try_cleanup(self):
    """Periodic cleanup task: remove expired objects from all pools."""
    alog.verbose('Object cache cleanup running')
    cleans = []
    with self._lock:
      new_cache = collections.defaultdict(collections.deque)
      for name, cqueue in self._cache.items():
        for entry in cqueue:
          age = time.time() - entry.time
          if age > entry.handler.max_age():
            cleans.append(entry)
          else:
            new_cache[name].append(entry)

      self._cache = new_cache

    for entry in cleans:
      alog.debug(f'Cache Clean: name={entry.name} obj={entry.obj}')
      entry.handler.close(entry.obj)

  def shutdown(self):
    """Stop the background cleaner."""
    self._cleaner.stop()

  def _release(self, name, handler, obj):
    """Return an object to the cache pool.

    Args:
      name: Cache pool name.
      handler: Handler instance for the object.
      obj: Object to return to the pool.
    """
    alog.debug(f'Cache Release: name={name} obj={obj}')
    with self._lock:
      self._cache[name].append(
          _Entry(name=name, obj=obj, handler=handler, time=time.time()))

  def get(self, name, handler):
    """Get an object from the cache or create a new one.

    Returns a FinWrapper that automatically returns the object to the
    cache when closed or garbage collected.

    Args:
      name: Cache pool name.
      handler: Handler instance defining object lifecycle.

    Returns:
      FinWrapper containing the object.
    """
    with self._lock:
      cqueue = self._cache[name]

    obj, closes = None, []
    while obj is None:
      with self._lock:
        entry = cqueue.popleft() if cqueue else None

      if entry is None:
        break

      if entry.handler.is_alive(entry.obj):
        obj = entry.obj
        alog.debug(f'Cache Hit: name={name} obj={obj}')
      else:
        closes.append(entry)

    # Handler calls can perform blocking I/O (e.g. FTP connect/close), so
    # they must run without holding the cache lock: a weakref finalizer
    # needing the lock from the peer thread of that same I/O would
    # deadlock the whole process.
    for entry in closes:
      alog.debug(f'Cache Close: name={entry.name} obj={entry.obj}')
      entry.handler.close(entry.obj)

    if obj is None:
      # Still no lock held: concurrent get() calls may each create an
      # object, the pool simply absorbs the surplus on release.
      obj = handler.create()

    finfn = functools.partial(self._release, name, handler, obj)

    return fw.FinWrapper(obj, finfn)

shutdown()

Stop the background cleaner.

Source code in py_misc_utils/object_cache.py
210
211
212
def shutdown(self):
  """Stop the background cleaner."""
  self._cleaner.stop()

get(name, handler)

Get an object from the cache or create a new one.

Returns a FinWrapper that automatically returns the object to the cache when closed or garbage collected.

Parameters:

Name Type Description Default
name

Cache pool name.

required
handler

Handler instance defining object lifecycle.

required

Returns:

Type Description

FinWrapper containing the object.

Source code in py_misc_utils/object_cache.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
def get(self, name, handler):
  """Get an object from the cache or create a new one.

  Returns a FinWrapper that automatically returns the object to the
  cache when closed or garbage collected.

  Args:
    name: Cache pool name.
    handler: Handler instance defining object lifecycle.

  Returns:
    FinWrapper containing the object.
  """
  with self._lock:
    cqueue = self._cache[name]

  obj, closes = None, []
  while obj is None:
    with self._lock:
      entry = cqueue.popleft() if cqueue else None

    if entry is None:
      break

    if entry.handler.is_alive(entry.obj):
      obj = entry.obj
      alog.debug(f'Cache Hit: name={name} obj={obj}')
    else:
      closes.append(entry)

  # Handler calls can perform blocking I/O (e.g. FTP connect/close), so
  # they must run without holding the cache lock: a weakref finalizer
  # needing the lock from the peer thread of that same I/O would
  # deadlock the whole process.
  for entry in closes:
    alog.debug(f'Cache Close: name={entry.name} obj={entry.obj}')
    entry.handler.close(entry.obj)

  if obj is None:
    # Still no lock held: concurrent get() calls may each create an
    # object, the pool simply absorbs the surplus on release.
    obj = handler.create()

  finfn = functools.partial(self._release, name, handler, obj)

  return fw.FinWrapper(obj, finfn)

cache()

Get the global singleton cache instance.

Returns:

Type Description

The global Cache instance.

Source code in py_misc_utils/object_cache.py
278
279
280
281
282
283
284
def cache():
  """Get the global singleton cache instance.

  Returns:
    The global Cache instance.
  """
  return _CACHE