Last active
May 31, 2018 07:55
-
-
Save allenyang79/81c452dbab8d40a30c7bb74839c09cc4 to your computer and use it in GitHub Desktop.
memorize_instance_method.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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