gpt4 book ai didi

Python:装饰器特定参数(与包装函数无关)?

转载 作者:太空狗 更新时间:2023-10-29 22:06:10 25 4
gpt4 key购买 nike

我希望构建一个缓存装饰器,它给定一个函数,将函数的结果缓存到装饰中指定的位置。像这样:

@cacheable('/path/to/cache/file')
def my_function(a, b, c):
return 'something'

装饰器的参数与它包装的函数的参数是完全分开的。我看过很多示例,但我不太明白如何执行此操作 - 是否可以为装饰器设置一个与包装函数无关且未传递给包装函数的参数?

最佳答案

想法是您的装饰器是一个返回装饰器的函数。

首先 编写您的装饰器,就好像您知道您的参数是一个全局变量一样。让我们这样说:

-

def decorator(f):
def decorated(*args,**kwargs):
cache = Cache(cachepath)
if cache.iscached(*args,**kwargs):
...
else:
res = f(*args,**kwargs)
cache.store((*args,**kwargs), res)
return res
return decorated

然后 编写一个将缓存路径作为参数并返回装饰器的函数。

-

def cache(filepath)
def decorator(f):
def decorated(*args,**kwargs):
cache = Cache(cachepath)
if cache.iscached(*args,**kwargs):
...
else:
res = f(*args,**kwargs)
cache.store((*args,**kwargs), res)
return res
return decorated
return decorator

关于Python:装饰器特定参数(与包装函数无关)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/660727/

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