您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

import json

def 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 code...

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

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

import json, atexit

def 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
python 2022/1/1 18:47:22 有469人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶