相关疑难解决方法(0)

Python - 任何人都有一个memoizing装饰器,可以处理不可用的参数?

我一直在使用下面的memoizing装饰器(来自伟大的书籍Python算法:掌握Python语言中的基本算法......喜欢它,顺便说一句).

def memo(func):
    cache = {}
    @ wraps(func)
    def wrap(*args):
        if args not in cache:
            cache[args] = func(*args)
        return cache[args]
    return wrap
Run Code Online (Sandbox Code Playgroud)

这个装饰器的问题是基于字典的缓存意味着我的所有参数都必须是可清除的.

有没有人有一个允许不可用的参数(例如字典)的实现(或对这一个的调整)?

我知道缺少哈希值意味着"这是否在缓存中?" 变得非常重要,但我只是想我会问.

===编辑给出上下文===

我正在开发一个函数,它返回一个Parnas风格的"使用层次结构"给定模块的字典:依赖项.这是设置:

def uses_hierarchy(requirements):
    """
    uses_hierarchy(requirements)

    Arguments:
    requirements - a dictionary of the form {mod: list of dependencies, }

    Return value:
    A dictionary of the form {level: list of mods, ...}

    Assumptions:
    - No cyclical requirements (e.g. if a requires b, b cannot require a).
    - Any dependency not listed as a mod assumed …
Run Code Online (Sandbox Code Playgroud)

python memoization

25
推荐指数
2
解决办法
1万
查看次数

标签 统计

memoization ×1

python ×1