gpt4 book ai didi

python - 如何在没有装饰器的情况下使用 lru_cache?适用于 3.8,不适用于 3.6

转载 作者:行者123 更新时间:2023-12-02 02:51:09 27 4
gpt4 key购买 nike

<分区>

我有一个昂贵的函数,我想使用 functools.lru_cache 缓存它,但仅在某些运行时条件下。

基于装饰器,没问题:

from functools import lru_cache


@lru_cache(maxsize=32)
def myfunc(a, b):
return a * b


print(myfunc(1,2))
print(myfunc(1,2))
print(myfunc(1,3))

print(f"cache_info:{myfunc.cache_info()}")

输出:

2
2
3
cache_info:CacheInfo(hits=1, misses=2, maxsize=32, currsize=2)

没有基于@的语法

但是,当我尝试先声明函数,然后有条件地将其包装在 lru_cache 中而不使用 @decorator 语法时,我遇到了问题。

from functools import lru_cache

def conditional_cached_func(a, b):
return a * b

some_system_dependent_value = True

if some_system_dependent_value:

cache_done = False


# 👇 I'm trying multiple calls to see what lru_cache expects
# only #3 works, but just so you don't replicate the other ones.
if not cache_done:

try:
conditional_cached_func = lru_cache(conditional_cached_func)
cache_done = True
print("#caching #1 worked")
except (Exception,) as e:
print(f"caching #1 error: {e}")

if not cache_done:

try:
conditional_cached_func = lru_cache(conditional_cached_func, maxsize=32)
cache_done = True
print("#caching #2 worked")
except (Exception,) as e:
print(f"caching #2 error: {e}")


if not cache_done:

try:
conditional_cached_func = lru_cache(32, conditional_cached_func)
cache_done = True
print("#caching #3 worked")
except (Exception,) as e:
print(f"caching #3 error: {e}")

#but in fact #3 doesn't work when called.
print(conditional_cached_func(2,2))
print(conditional_cached_func(2,2))
print(conditional_cached_func(2,3))


if some_system_dependent_value:

print(f"conditional_cache_info:{conditional_cached_func.cache_info()}")

输出:


cache_info:CacheInfo(hits=1, misses=2, maxsize=32, currsize=2)
caching #1 error: Expected maxsize to be an integer or None
caching #2 error: lru_cache() got multiple values for argument 'maxsize'
#caching #3 worked
Traceback (most recent call last):
File "test_147_lrucache.py", line 56, in <module>
print(conditional_cached_func(2,2))
TypeError: decorating_function() takes 1 positional argument but 2 were given

我使用的是 Python 3.6,我提到 3.8 显然已经对可能相关的装饰器的某些方面进行了调整。

实际上,它在 3.8 下工作,语法 #1

我需要在 3.6 下做什么?

#caching #1 worked
4
4
6
conditional_cache_info:CacheInfo(hits=1, misses=2, maxsize=128, currsize=2)

如果您真的、真的、很好奇……这是在访问一个几乎只读的数据库。在运行测试时,可以假定我用于内省(introspection)数据库的昂贵函数的结果是静态的并且不会改变。在实时条件下,这些结果随时可能发生变化,但用户几乎不会看它们。

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com