记忆到磁盘-python-永久记忆

记忆到磁盘-python-永久记忆,第1张

记忆到磁盘-python-永久记忆

Python提供了一种非常优雅的方式来执行此 *** 作-装饰器。基本上,装饰器是一个包装另一个功能以提供其他功能而不更改功能源代码的功能。您的装饰器可以这样写:

import jsondef persist_to_file(file_name):    def decorator(original_func):        try: cache = json.load(open(file_name, 'r'))        except (IOError, ValueError): cache = {}        def new_func(param): if param not in cache:     cache[param] = original_func(param)     json.dump(cache, open(file_name, 'w')) return cache[param]        return new_func    return decorator

一旦知道了,就可以使用@ -syntax“装饰”函数,您就可以准备就绪了。

@persist_to_file('cache.dat')def html_of_url(url):    your function pre...

请注意,此修饰器是有意简化的,可能不适用于所有情况,例如,当源函数接受或返回无法进行json序列化的数据时。

有关装饰器的更多信息:如何制作功能装饰器链?

这是使装饰器在退出时仅保存一次缓存的方法:

import json, atexitdef persist_to_file(file_name):    try:        cache = json.load(open(file_name, 'r'))    except (IOError, ValueError):        cache = {}    atexit.register(lambda: json.dump(cache, open(file_name, 'w')))    def decorator(func):        def new_func(param): if param not in cache:     cache[param] = func(param) return cache[param]        return new_func    return decorator


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5673534.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存