这个 ‘nonlocal’ 关键字在这个装饰器中是做什么的?

huangapple go评论90阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年7月27日 22:10:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76780596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定