Python 中装饰器缓存的困惑

问题描述 投票:0回答:1

我正在使用 Python 装饰器来实现函数的缓存。我了解缓存结果以提高性能的基本概念,但我正在努力解决如何处理不同的函数参数并确保底层数据更改时缓存更新。

我实现了一个基本的装饰器,它根据参数将函数结果存储在字典中。但是,这种方法无法处理函数参数可能具有复杂结构(如嵌套列表)或函数所依赖的基础数据可能被修改的情况。

def simple_cache(func):
  cache = {}
  def wrapper(*args, **kwargs):
    key = (args, kwargs)  # Basic key based on arguments
    if key not in cache:
      cache[key] = func(*args, **kwargs)
    return cache[key]
  return wrapper

@simple_cache
def calculate_something(data):
  # Simulates complex calculation
  # ...
  return result
python function caching arguments decorator
1个回答
0
投票

这是理解缓存机制的一个很好的尝试。 但是,如果您确实想在更复杂的用例中使用缓存,则应该选择 Python 内置缓存(自 Python 3.9 起),它完全可以实现您想要的功能(示例取自官方文档)。

from functools import cache

@cache
def factorial(n):
    return n * factorial(n-1) if n else 1

>>> factorial(10)      # no previously cached result, makes 11 recursive calls
3628800
>>> factorial(5)       # just looks up cached value result
120
>>> factorial(12)      # makes two new recursive calls, the other 10 are cached
479001600
© www.soinside.com 2019 - 2024. All rights reserved.