Login

Automatic Memoization Decorator

Author:
nikmolnar
Posted:
January 5, 2013
Language:
Python
Version:
1.7
Tags:
cache memoize
Score:
1 (after 1 ratings)

This decorator will memoize the results of instance methods, similar to django.util.functional.memoize, but automatically creates a cache attached to the object (and therefore shares the life span of the object) rather than requiring you to provide your own. Note this is intended for instance methods only, though it may work in some cases with functions and class methods with at least one argument.

This is useful for memozing results of model methods for the life of a request. For example:

class MyModel(models.Model):
    #Fields here

    @auto_memoize
    def some_calculation(self):
        #some calculation here
        return result
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
from functools import wraps

def auto_memoize(func):
	"""
	Based on django.util.functional.memoize. Automatically memoizes instace methods for the lifespan of an object.
	Only works with methods taking non-keword arguments. Note that the args to the function must be usable as
	dictionary keys. Also, the first argument MUST be self. This decorator will not work for functions or class methods,
	only object methods.
	"""

	@wraps(func)
	def wrapper(*args):
		inst = args[0]
		inst._memoized_values = getattr(inst, '_memoized_values', {})
		key = (func,args[1:])
		if key not in inst._memoized_values:
			inst._memoized_values[key] = func(*args)
		return inst._memoized_values[key]
	return wrapper

More like this

  1. Function decorator for caching function results in local memory by bikeshedder 2 years, 10 months ago
  2. Cachable Class Method Decorator by amitu 6 years, 9 months ago
  3. Inject request into functions by lorinkoz 4 weeks, 1 day ago
  4. Method Caching by bryanhelmig 4 years, 1 month ago
  5. Run and cache only one instance of a heavy request by farnsworth 4 years, 11 months ago

Comments

Please login first before commenting.