简体   繁体   中英

Declaring a function parameter inside a decorator

I need to create parameters inside the decorator so as not to duplicate code in several methods, however, I ran into an error, and I'm not sure how such work with namespace is correct. I would like to know how generally such a construction is acceptable in the program and is it worth using it?

My attempt looks like this:

import configparser
import os


def save_settings(func):
    def wrapper(*args, **kwargs):
        path_to_settings = os.path.join("setting", "config.ini")
        config = configparser.ConfigParser()
        config.read(path_to_settings, encoding="utf-8")

        config = func(*args, **kwargs)

        with open(path_to_settings, 'w') as configfile:
            config.write(configfile)
    return wrapper


@save_settings
def change_STORAGE_FOLDER(name):
    config["parameter"]["STORAGE_FOLDER"] = f"{name}"
    return config


@save_settings
def change_ALLOWED_EXTENSIONS(value):
    config["parameter"]["ALLOWED_EXTENSIONS"] = f"{value}"
    return config

change_STORAGE_FOLDER("Folder_img")

| NameError: name 'config' is not defined

Moreover, if we place the function directly, and not as an argument, then we will not get errors:

import configparser
import os

def wrapper():
    path_to_settings = os.path.join("setting", "config.ini")
    config = configparser.ConfigParser()
    config.read(path_to_settings, encoding="utf-8")

    def change_STORAGE_FOLDER(name):
        config["parameter"]["STORAGE_FOLDER"] = f"{name}"
        return config
    config = change_STORAGE_FOLDER("Folder_img")


    with open(path_to_settings, 'w') as configfile:
        config.write(configfile)

wrapper()

You're correct, your function variables are local not global. There are a number of solutions -- the easiest of which is changing your config write to a method and adding it into each function

import configparser
import os

def write_config(config):
    path_to_settings = os.path.join("setting", "config.ini")
    config = configparser.ConfigParser()
    config.read(path_to_settings, encoding="utf-8")

    with open(path_to_settings, 'w') as configfile:
        config.write(configfile)

def change_STORAGE_FOLDER(name):
    config["parameter"]["STORAGE_FOLDER"] = f"{name}"
    write_config(config)
    return config

def change_ALLOWED_EXTENSIONS(value):
    config["parameter"]["ALLOWED_EXTENSIONS"] = f"{value}"
    write_config(config)
    return config

change_STORAGE_FOLDER("Folder_img")

Other methods such as bundling it all as a class or declairing it as a global variable also work, depending on your use case

edit: I realized you were running funk inside each of the change methods

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM