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.
>Solution :
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