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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.