Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is this 'nonlocal' keyword is doing is this decorator?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading