Automatic Memoization Decorator

 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 1 year, 7 months ago
  2. Cachable Class Method Decorator by amitu 5 years, 6 months ago
  3. Method Caching by bryanhelmig 2 years, 9 months ago
  4. Run and cache only one instance of a heavy request by farnsworth 3 years, 8 months ago
  5. Stales Cache Class Method Decorator by amitu 5 years, 6 months ago

Comments

(Forgotten your password?)