Skip to content

Instantly share code, notes, and snippets.

@allenyang79
Last active May 31, 2018 07:55
Show Gist options
  • Save allenyang79/81c452dbab8d40a30c7bb74839c09cc4 to your computer and use it in GitHub Desktop.
Save allenyang79/81c452dbab8d40a30c7bb74839c09cc4 to your computer and use it in GitHub Desktop.
memorize_instance_method.py
import random
import functools
import json
import weakref
import time
import sys
import gevent
class memoize(object):
def __init__(self, function):
self._caches = weakref.WeakKeyDictionary()
self._function = function
@functools.wraps(function)
def wrapd(instance, *args, **kw):
if instance not in self._caches:
self._caches[instance] = {}
cache_key = json.dumps([args, kw], sort_keys=True)
if cache_key not in self._caches[instance]:
self._caches[instance][cache_key] = self._function(instance, *args, **kw)
return self._caches[instance][cache_key]
self.wrapd = wrapd
def __get__(self, instance, cls=None):
if instance:
return functools.partial(self.wrapd, instance)
return self
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment