|
1 | 1 | """Extensible memoizing decorator helpers."""
|
2 | 2 |
|
3 | 3 |
|
| 4 | +def _cached_cond_info(func, cache, key, cond, info): |
| 5 | + hits = misses = 0 |
| 6 | + pending = set() |
| 7 | + |
| 8 | + def wrapper(*args, **kwargs): |
| 9 | + nonlocal hits, misses |
| 10 | + k = key(*args, **kwargs) |
| 11 | + with cond: |
| 12 | + cond.wait_for(lambda: k not in pending) |
| 13 | + try: |
| 14 | + result = cache[k] |
| 15 | + hits += 1 |
| 16 | + return result |
| 17 | + except KeyError: |
| 18 | + pending.add(k) |
| 19 | + misses += 1 |
| 20 | + try: |
| 21 | + v = func(*args, **kwargs) |
| 22 | + with cond: |
| 23 | + try: |
| 24 | + cache[k] = v |
| 25 | + except ValueError: |
| 26 | + pass # value too large |
| 27 | + return v |
| 28 | + finally: |
| 29 | + with cond: |
| 30 | + pending.remove(k) |
| 31 | + cond.notify_all() |
| 32 | + |
| 33 | + def cache_clear(): |
| 34 | + nonlocal hits, misses |
| 35 | + with cond: |
| 36 | + cache.clear() |
| 37 | + hits = misses = 0 |
| 38 | + |
| 39 | + def cache_info(): |
| 40 | + with cond: |
| 41 | + return info(hits, misses) |
| 42 | + |
| 43 | + wrapper.cache_clear = cache_clear |
| 44 | + wrapper.cache_info = cache_info |
| 45 | + return wrapper |
| 46 | + |
| 47 | + |
4 | 48 | def _cached_locked_info(func, cache, key, lock, info):
|
5 | 49 | hits = misses = 0
|
6 | 50 |
|
@@ -139,6 +183,8 @@ def _cached_wrapper(func, cache, key, lock, info):
|
139 | 183 | wrapper = _uncached_info(func, info)
|
140 | 184 | elif lock is None:
|
141 | 185 | wrapper = _cached_unlocked_info(func, cache, key, info)
|
| 186 | + elif hasattr(lock, "wait_for") and hasattr(lock, "notify_all"): |
| 187 | + wrapper = _cached_cond_info(func, cache, key, lock, info) |
142 | 188 | else:
|
143 | 189 | wrapper = _cached_locked_info(func, cache, key, lock, info)
|
144 | 190 | else:
|
|
0 commit comments