gpt4 book ai didi

python - 装饰器工厂参数是静态值而不是变量值

转载 作者:太空宇宙 更新时间:2023-11-03 23:58:08 27 4
gpt4 key购买 nike

所以我有

# my decorator factory
def execute_in(directory): # <-- I want this to be a variable's value which can change
def decorator(function):
def wrapper(*args, **kwargs):
os.chdir(directory)
print(directory) # currently is printing None which is my problem
value = function(*args, **kwargs)
os.chdir(home_dir)
return value
return wrapper
return decorator

# a function that runs after assigning General.archive_dir a value
@execute_in(General.archive_dir)
def get_data():
print(General.archive_dir) # will print the correct directory name
with open('data.csv', 'r') as f:
rows = [row for row in csv.reader(f, delimiter=',')]
return rows

我的问题是,装饰器工厂正在使用程序启动时实例化的变量 General.archive_dir 的值,当时它的值为 None。我希望它在调用修饰函数时使用 General.archive_dir 的值。我该怎么做?

如果这个问题不清楚,我深表歉意。如果可以,请告诉我如何在需要时进行澄清。

最佳答案

一种解决方案是使用 lambda 调用 @execute_in

wrapper 内的

directory 将成为一个函数,在调用时返回当前值。

archive_dir = None

# decorator factory
def execute_in(directory_path_getter):
def decorator(function):
def wrapper(*args, **kwargs):
print('from wrapper:', directory_path_getter()) # Notice the function call
value = function(*args, **kwargs)
return value
return wrapper
return decorator

@execute_in(lambda: archive_dir)
def get_data():
...

archive_dir = 'some directory'

print(get_data())

打印:

from wrapper: some directory
from get_data: some directory
['some data']

关于python - 装饰器工厂参数是静态值而不是变量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56785009/

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