Skip to content

Instantly share code, notes, and snippets.

@arkanister
Created April 24, 2019 13:14
Show Gist options
  • Select an option

  • Save arkanister/62c20d9312a59c284bd65bf2e524d5a3 to your computer and use it in GitHub Desktop.

Select an option

Save arkanister/62c20d9312a59c284bd65bf2e524d5a3 to your computer and use it in GitHub Desktop.
Cache function results on the instance.
"""
@author: arkanister;
"""
def cache_it(method=None, name=None):
"""
Decorator to cache a function result in the class.
Using this is expected that the function can only be called once by instance,
which means that the second time the function is called, the cached result
will be displayed instead process the content again.
IMPORTANT: It must be only used in class methods.
Args:
method (required) - Method to be decorated.
name (string, optional) - Property name to store the cached value on
the class, the prefix _cached_ will be added to this name. In case None
value the name of the function will be considered.
Returns:
decorated function.
Usage:
>>> @cache_it(name='name')
>>> def get_name(self):
>>> ...
or
>>> @cache_it
>>> def get_name(self):
>>> ...
"""
def wrapper(func):
# get the property name to store the
# function result.
prop = name or func.__name__
prop = '_cached_%s' % prop
def wrap(self, *args, **kwargs):
if not hasattr(self, prop):
# if the property does not exists yet,
# call the function to get the result and store,
# it result in the property.
setattr(self, prop, func(self, *args, **kwargs))
# return the cached result.
return getattr(self, prop)
return wrap
if callable(method):
# just in case of `@cache_it` definition.
return wrapper(method)
# return the decorated function.
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment