英文:
What is this 'nonlocal' keyword is doing is this decorator?
问题
我创建了这个装饰器来将函数的输出保存到一个CSV文件中(以便团队可以轻松阅读)。
def save_to_csv(directory, file_name = None):
def decorator(func):
def wrapper(*args, **kwargs):
value = func(*args, **kwargs)
# 我注释掉了建议使用的"nonlocal"关键字,但代码在使用它的情况下仍然可以正常工作,这些情况是:
if file_name is None:
file_name = input("不带扩展名的文件名: ")
file_path = os.path.join(directory, f"{file_name}.csv")
with open(os.path.join(directory, file_name, ".csv"), 'w') as file:
file.write(value)
return value
return wrapper
return decorator
但正如你所看到的,我评论掉了建议的"nonlocal"关键字,而代码在使用它的情况下仍然可以正常工作,这些情况是:
@save_to_csv
def calculate_saidi(self, bus,*, file_name):
...
和
save_data_to_csv = save_to_cvs(dir, f"{bus_name}")(self.calculate_worse_case)
我搜索了"nonlocal"关键字的用法,但我无法理解它在这种情况下甚至在一般情况下的用处。
你是否建议我取消注释它?
如果你感兴趣的话,可以随意评判和询问我的代码。
英文:
I created this decorator to save the output of a function to a csv file (so the team can easily read it).
def save_to_csv(directory, file_name = None):
def decorator(func):
def wrapper(*args, **kwargs):
value = func(*args, **kwargs)
# nonlocal file_name idk what this is doing but it works without it
if file_name is None:
file_name = input("File name without extension: ")
file_path = os.path.join(directory, f"{file_name}.csv")
with open(os.path.join(directory, file_name, ".csv"), 'w') as file:
file.write(value)
return value
return wrapper
return decorator
But as you can see, I commented the sugested nonlocal
keyword, and the code still works fine for the cases its used on that are:
@save_to_csv
def calculate_saidi(self, bus,*, file_name):
...
And
save_data_to_csv = save_to_cvs(dir, f"{bus_name}")(self.calculate_worse_case)
Searched for the uses of the nonlocal keyword, but I can't understand it's usefullness in this case and even in general.
Would you recomend I uncomment it?
Feel free to judge and ask about my code if you feel like it.
答案1
得分: 1
你可以使用 nonlocal
关键字来覆盖更高命名空间的变量。
例如,你可以在 decorator
函数的开头定义 file_name
,然后在 wrapper
函数内部覆盖它的值。
在你的特定情况下,它不是必需的或有用的,因为它不需要访问 file_name
。
英文:
You use the nonlocal
keyword to overwrite variables of a higher namespace.
For example, you could define the file_name
at the beginning of the decorator
function and overwrite its value inside the wrapper
function.
It isn't needed or usefull in your specific case because it doesn't need access to file_name
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论