[PYTHON] It can be achieved in 1 minute! Decorator that caches function execution results in memcached

This alone can cache the return value in memcached


@cached(time=1200)
def functionToCache(arguments):
  return arguments

When is it convenient?

Especially, I find it convenient when doing scraping and development involving external data.

How to use

  1. Do pip install python-memcached
  2. Save the following python file in a suitable place and import the cached function
  3. When defining a function, decorate it in a format like @cached (time = 1000)

Snippet

memcached-decorater.py


def decorator_with_args(decorator_to_enhance):
  """ 
A function that gives an argument to the decorator and returns it
  """
  def decorator_maker(*args, **kwargs) :
    def decorator_wrapper(func) :
      return decorator_to_enhance(func, *args, **kwargs)
    return decorator_wrapper
  return decorator_maker

@decorator_with_args
def cached(func, *args, **kwargs):
  """
Decorator that caches results using function names and arguments as keys
How to use
    @cached(time=1200)
    def functionToCache(arguments):
  """
  def wrapper(*pars):
    key = func.__name__ + '_' + '_'.join([str(par) for par in pars])
    print key
    client = memcache.Client(['127.0.0.1:11211'])
    val = client.get(key)
    if not val:
      val = func(*pars)
      try:
        client.set(key, val, time=kwargs['time'])
      except:
        pass #Please
    return val
  return wrapper


reference

gae-memcache-decorator.py https://gist.github.com/abahgat/1395810

Recommended Posts

It can be achieved in 1 minute! Decorator that caches function execution results in memcached
Maximum number of function parameters that can be defined in each language
I made a familiar function that can be used in statistics with Python
Functions that can be used in for statements
Building Sphinx that can be written in Markdown
Morphological analysis and tfidf (with test code) that can be done in about 1 minute
Basic algorithms that can be used in competition pros
ANTs image registration that can be used in 5 minutes
It seems that Skeleton Tracking can be done with RealSense
Text analysis that can be done in 5 minutes [Word Cloud]
Goroutine that can be used in the field (errgroup.Group edition)
Scripts that can be used when using bottle in Python
Evaluation index that can be specified in GridSearchCV of sklearn
I made it because I want JSON data that can be used freely in demos and prototypes
Can it be done in 1 minute? No installation required, Google Test sample for C language for Linux
・ <Slack> Write a function to notify Slack so that it can be quoted at any time (Python)