python - 有条件内存?

标签 python decorator python-2.6 memoization python-decorators

那里有很多记忆化装饰器,但我很好奇如何编写一个支持任意函数签名的记忆化装饰器,但让函数决定何时内存结果?像这样的事情:

def conditional_memoize(f):
    cache = {}
    @wraps(f)
    def conditional_f(*args, **kwargs):
        return f(*args, **kwargs)
    return conditional_f

@conditional_memoize
def my_func(a, b, c):
    if str(a) + str(b) + str(c) in cache:
        return cache[str(a) + str(b) + str(c)]
    res = # compute the result
    if some_arbitrary_condition:
        cache[str(a) + str(b) + str(c)] = res
    return res

但是,我知道由于 NameError,这不会起作用。无论如何,有一个聪明的方法来解决这个问题吗?我总是可以使用类方法和类缓存,只是想看看是否有一个装饰器模式。

最佳答案

让函数返回其所需的结果和指示是否应缓存结果的标志,或者让包装器将缓存对象传递给函数。 (或两者兼而有之!)无论哪种方式都可以,但我更喜欢第一种方法。也许是这样的......

import functools

def conditional_memoize(fn):
    cache = {}

    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        key = args + tuple(sorted(kwargs.iteritems()))
        if key in cache:
            return cache[key]
        result, flag = fn(*args, **kwargs)
        if flag:
            cache[key] = result
        return result

    return wrapper

关于python - 有条件内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19599439/

相关文章:

Python 在绘图中使用自定义颜色

python - 科学数据包 : What's the easiest way to get the confusion matrix of an estimator when using GridSearchCV?

python - 无法使用 selenium + python 在控制台中获得 "print"输出

python - 怎么 "mark"一组Python方法供以后使用? (这些装饰器可以改进吗?)

Python正则表达式匹配特定的字符序列

python - 如何在 Python 中循环 optparse.OptionGroup

python - 机器学习 - 如何根据过去的特征预测一组固定字段

java - 显示装饰器模式

python - 'function'对象在django中没有属性 'get'

get-pip.py 的 curl 不起作用 : Syntax Error