Skip to content

Instantly share code, notes, and snippets.

@ericmoritz
Created October 4, 2013 15:29
Show Gist options
  • Select an option

  • Save ericmoritz/6827844 to your computer and use it in GitHub Desktop.

Select an option

Save ericmoritz/6827844 to your computer and use it in GitHub Desktop.
def modify_cache(cache, key, timeout, callback):
"""
A abstraction from the common, cache.get, if None, cache.set pattern.
Test an uncached value:
>>> cache = __mock_cache(None)
>>> modify_cache(cache, 'foo', 1000, lambda: 1)
1
>>> cache.get.assert_called_with('foo')
>>> cache.set.assert_called_with('foo', 1, 1000)
Test a cached value:
>>> cache = __mock_cache(1)
>>> modify_cache(cache, 'bar', 1000, lambda: 2)
1
>>> cache.get.assert_called_with('bar')
>>> cache.set.called
False
"""
ret = cache.get(key)
if ret is None:
ret = callback()
cache.set(key, ret, timeout)
return ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment