相关疑难解决方法(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万
查看次数

使用functools的@lru_cache而不指定maxsize参数

给出函数定义的文档lru_cache:

@functools.lru_cache(maxsize=128, typed=False)
Run Code Online (Sandbox Code Playgroud)

这对我说maxsize是可选的.

但是,它不喜欢没有参数调用:

Python 3.6.3 (default, Oct 24 2017, 14:48:20) 
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import functools
>>> @functools.lru_cache
... def f(): ...
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.6/functools.py", line 477, in lru_cache
    raise TypeError('Expected maxsize to be an integer or None')
TypeError: Expected maxsize to be an integer or None
 >>> 
Run Code Online (Sandbox Code Playgroud)

使用参数调用很好:

>>> @functools.lru_cache(8)
... …
Run Code Online (Sandbox Code Playgroud)

python caching lru functools

5
推荐指数
2
解决办法
2495
查看次数

标签 统计

python ×2

caching ×1

functools ×1

lru ×1

memoization ×1