Login

Function decorator for caching function results in local memory

Author:
bikeshedder
Posted:
September 24, 2012
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)
@cache(60)
def heavy_computation():
   for x in xrange(10000000):
       pass # just waste some time`

The result of heavy_computation calls will be cached for 60 seconds. This cache decorator does not use the Django cache backend and uses the local memory instead.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from time import time

class cache(object):
    def __init__(self, seconds):
        self.seconds = seconds
        self.value = None
        self.timestamp = None
    def __call__(self, f):
        def cached():
            now = time()
            if now - self.seconds > self.timestamp:
                self.value = f()
                self.timestamp = now
            return self.value
        return cached

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 3 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.