Login

Automatic Memoization Decorator

Author:
nikmolnar
Posted:
January 5, 2013
Language:
Python
Version:
1.7
Score:
2 (after 2 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. 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, 2 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.