Memoization decorator for a function taking one or more arguments.
6317
def memoize(f):
    
    class memodict(dict):

        def __getitem__(self, *key):
            return dict.__getitem__(self, key)

        def __missing__(self, key):
            ret = self[key] = f(*key)
            return ret

    return memodict().__getitem__
897110
def cache(cls, key_attrs, expires=None):
        

        def decorator(func):

            @functools.wraps(func)
            def wrapper(self, *args, **kwargs):
                module = type(self).__module__
                classname = type(self).__name__
                method_name = func.__name__

                data = {}
                if isinstance(key_attrs, basestring):
                    _key_attrs = key_attrs.split()
                else:
                    _key_attrs = key_attrs
                for key_attr in _key_attrs:
                    key_value = getattr(self, key_attr)
                    if isinstance(key_value, dict):
                        key_value = ('dict', sorted(key_value.items()))
                    elif isinstance(key_value, set):
                        key_value = ('set', sorted(key_value))
                    else:
                        key_value = (type(key_value).__name__, key_value)
                    data[key_attr] = key_value
                data = sorted(data.items())

                result_cache, new = cls.get_or_create(
                    module=module,
                    classname=classname,
                    method_name=method_name,
                    data=data,
                    args=args,
                    kwargs=sorted(kwargs.items()),
                )

                if new:
                    result_cache.result = func(self, *args, **kwargs)
                    result_cache.save(expires)

                return result_cache.result

            return wrapper

        return decorator
108523
public static <T, R> Function1<T, R> memoizeFunction(final Function<T, R> fn, final Cacheable<R> cache) {
        LazyImmutable<R> nullR = LazyImmutable.def();
        return t -> t==null? nullR.computeIfAbsent(()->fn.apply(null)) : (R)cache.soften()
                         .computeIfAbsent(t, (Function) fn);
    }
784367
def expiring_memoize(obj):
    """"""

    cache = obj.cache = {}
    last_access = obj.last_access = defaultdict(int)

    @wraps(obj)
    def memoizer(*args, **kwargs):
        key = str(args) + str(kwargs)

        if last_access[key] and last_access[key] + 10 < time():
            if key in cache:
                del cache[key]

        last_access[key] = time()

        if key not in cache:
            cache[key] = obj(*args, **kwargs)
        return cache[key]

    return memoizer
831316
def memoize(fn):
    
    cache = {}

    @wraps(fn)
    def wrapped_fn(*args, **kwargs):
        cache_key = _memoize_cache_key(args, kwargs)
        try:
            return cache[cache_key]
        except KeyError:
            value = fn(*args, **kwargs)
            cache[cache_key] = value
            return value

    def clear_cache():
        cache.clear()

    # Needed to ensure that EnsemblRelease.clear_cache
    # is able to clear memoized values from each of its methods
    wrapped_fn.clear_cache = clear_cache
    # expose the cache so we can check if an item has already been computed
    wrapped_fn.cache = cache
    # if we want to check whether an item is in the cache, first need
    # to construct the same cache key as used by wrapped_fn
    wrapped_fn.make_cache_key = _memoize_cache_key
    return wrapped_fn
814392
def memoized(maxsize=1024):
    
    cache = SimpleCache(maxsize=maxsize)

    def decorator(obj):
        @wraps(obj)
        def new_callable(*a, **kw):
            def create_new():
                return obj(*a, **kw)

            key = (a, tuple(kw.items()))
            return cache.get(key, create_new)
        return new_callable
    return decorator
61742
public static <T1, T2, T3, T4, R> Function4<T1, T2, T3, T4, R> memoizeQuadFunction(final Function4<T1, T2, T3, T4, R> fn) {
      Function1<Tuple4<T1, T2, T3, T4>, R> memoise2 = memoizeFunction((final Tuple4<T1, T2, T3, T4> quad) -> fn.apply(quad._1(), quad._2(), quad._3(), quad._4()));
        return (t1, t2, t3, t4) -> memoise2.apply(tuple(t1, t2, t3, t4));
    }
478056
def decorator(func):
        """"""

        def function_timer(*args, **kwargs):
            """A nested function for timing other functions."""
            # Capture start time
            start = time.time()

            # Execute function with arguments
            value = func(*args, **kwargs)

            # Capture end time
            end = time.time()

            # Calculate run time
            runtime = end - start
            if runtime < 60:
                runtime = str('sec: ' + str('{:f}'.format(runtime)))
            else:
                runtime = str('min: ' + str('{:f}'.format(runtime / 60)))
            print('{func:50} --> {time}'.format(func=func.__qualname__, time=runtime))
            return value

        return function_timer
919202
def decorator(caller, func=None):
    
    if func is None: # returns a decorator
        fun = FunctionMaker(caller)
        first_arg = inspect.getargspec(caller)[0][0]
        src = 'def %s(%s): return _call_(caller, %s)' % (
            caller.__name__, first_arg, first_arg)
        return fun.make(src, dict(caller=caller, _call_=decorator),
                        undecorated=caller)
    else: # returns a decorated function
        fun = FunctionMaker(func)
        src = """def %(name)s(%(signature)s):
    return _call_(_func_, %(signature)s)"""
        return fun.make(src, dict(_func_=func, _call_=caller), undecorated=func)
106777
def decorator(caller, _func=None):
    """"""
    if _func is not None:  # return a decorated function
        # this is obsolete behavior; you should use decorate instead
        return decorate(_func, caller)
    # else return a decorator function
    if inspect.isclass(caller):
        name = caller.__name__.lower()
        doc = 'decorator(%s) converts functions/generators into ' \
              'factories of %s objects' % (caller.__name__, caller.__name__)
    elif inspect.isfunction(caller):
        if caller.__name__ == '<lambda>':
            name = '_lambda_'
        else:
            name = caller.__name__
        doc = caller.__doc__
    else:  # assume caller is an object with a __call__ method
        name = caller.__class__.__name__.lower()
        doc = caller.__call__.__doc__
    evaldict = dict(_call_=caller, _decorate_=decorate)
    return FunctionMaker.create(
        '%s(func)' % name, 'return _decorate_(func, _call_)',
        evaldict, doc=doc, module=caller.__module__,
        __wrapped__=caller)
632377
def memoized_ignoreargs(func):
    
    def wrapper(*args, **kwargs):
        if func not in _MEMOIZED_NOARGS:
            res = func(*args, **kwargs)
            _MEMOIZED_NOARGS[func] = res
            return res
        return _MEMOIZED_NOARGS[func]
    return wrapper
1368103
def memorize(func):
    
    @wraps(func)
    def wrapped_func(*args, **kwargs):
        if (len(args) > 0 and len(kwargs) > 0): 
            cacheKey = list(args)
            cacheKey.append(kwargs)
        elif (len(args) > 0): 
            cacheKey = args
        else:
            cacheKey = func.__name__
            
        global __cache__
        result = __cache__.get(cacheKey)
        if result is None:
            result = func(*args, **kwargs)
            __cache__[cacheKey] = result
        return result

    return wrapped_func
217492
def decorator(func):
  
  """
  def wrapper(__decorated__=None, *Args, **KwArgs):
    if __decorated__ is None: # the decorator has some optional arguments.
      return lambda _func: func(_func, *Args, **KwArgs)

    else:
      return func(__decorated__, *Args, **KwArgs)

  return wrap(wrapper, func)
389137
def memoize_single_argument(f):
    
    class memodict(dict):

        def __missing__(self, key):
            ret = self[key] = f(key)
            return ret
    return memodict().__getitem__
75709
def argument(*args, **kwargs):
    
    def decorator(f):
        if not hasattr(f, '_arguments'):
            f._arguments = []
        if not hasattr(f, '_argnames'):
            f._argnames = []
        f._arguments.append((args, kwargs))
        f._argnames.append(_get_dest(*args, **kwargs))
        return f
    return decorator
1210353
def safe_wraps(wrapper, *args, **kwargs):
    """"""
    while isinstance(wrapper, functools.partial):
        wrapper = wrapper.func
    return functools.wraps(wrapper, *args, **kwargs)
488372
def memoize(func):
    """"""
    cache = {}

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        """Caching wrapper."""
        key = (args, tuple(sorted(kwargs.items())))
        if key in cache:
            return cache[key]
        else:
            result = func(*args, **kwargs)
            cache[key] = result
            return result

    return wrapper