包装器,用于检查现有数据的众多功能

时间:2014-02-11 08:59:45

标签: python python-decorators

如果是这样,请不要犹豫,将问题视为重复。 :)

在我的代码中,我有很多看起来像

的块
try:
    load_from_disk(pathtofile)
except IOError:
    datapiece = comp_this_data( **dictofargs )
    save_to_disk(pathtofile, datapiece)

问题:如何定义处理不同comp_this_data可能的预先计算数据的例程?

也许,对于python装饰器来说这是一个简单的例子。但是,据我所知,装饰器是函数定义的一部分,我不想改变它。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

以下是如何包装多个计算函数的示例:

def compute_and_save(compute_f, file, *args, **kwargs):
    try:
        load_from_disk(file)
    except IOError:
        datapiece = compute_f(*args, **kwargs)
        save_to_disk(file, datapiece)

if __name__ == "__main__":
    compute_and_save(comp_this_data, file, **dictofargs)
    compute_and_save(comp_this_data_2, file, **dictofargs)