簡體   English   中英

在Python中清晰地記住整個塊/匿名函數

[英]Memoize entire block / anonymous function cleanly in Python

用Python記住整個計算塊(多行lambda,如果可以創建的話)的最干凈方法是(從用戶方面)?

使用備忘錄時,我打算使用一個通用的“如果已經計算出結果,則從某個地方加載它。否則將其計算並保存到某個地方。”

我目前的解決方案(用於將任意計算結果緩存到磁盤的內容寫入):

  1. 有一個裝飾器來進行緩存(它將文件名保存/加載到的位置作為參數):
from functools import wraps

def disk_cache(filename):
    def decorator(compute_result_func):
        @wraps(compute_result_func) # don't shadow function's docstring
        def wrapped(*args, **kwargs):
            if not os.path.exists(filename):
                # compute and save
                print "compute"
                result = compute_result_func()
                print "save"
                pickle.dump(result, open(filename, 'wb'))
            else:
                # load
                print "load"
                result = pickle.load(open(filename, 'rb'))
            return result
        return wrapped
    return decorator
  1. 每當我有一個要記住的計算塊時,我會將其包裝到一個具有通用名稱(如果可以的話,我將使用多行lambda)的函數,該函數什么都不做(只是捕獲更大范圍內的變量)並返回一個結果。 我用裝飾器裝飾了此函數,然后立即調用該函數。
@disk_cache(filename='/path/to/dump.pkl')
def multi_line_lambda():
    # do some stuff
    x = 2 ** 2
    y = 7
    return x + y
multi_line_lambda()

是否可以使用語法上更簡潔的模式? 就像是

with cache(filename):
    do x
    do y
    return result # which is actually just loaded if already existing

過去,我探討了這個確切的問題(無恥的插件:這是我的結果 ),發現最好使用現有的方法。 但是,如果您願意濫用Python語法,可以按照以下方法進行操作:

def disk_cache(filename):
    def decorator(compute_result_func):
        if not os.path.exists(filename):
            result = compute_result_func()
            pickle.dump(result, open(filename, 'wb'))
        else:
            result = pickle.load(open(filename, 'rb'))
        return result
    return decorator

現在,

@disk_cache(filename='/path/to/dump.pkl')
def calculated_stuff():
    # do some stuff
    x = 2 ** 2
    y = 7
    return x + y
# at this point, calculated_stuff() already contains the result (11)

請記住這是一種骯臟的做法。 不要用別人可以閱讀的代碼來做

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM