在函数调用中使用返回值的最佳实践

问题描述 投票:0回答:0

为我的实用程序制作了一个基本的 Python,这是我学习如何编码的第一个项目,我知道它很混乱,这就是我来这里的原因。

在这个program中,“Upload XML File”下面的按钮调用了函数“browseXMLFiles”,“Upload LOG File”下面的按钮调用了“browseLOGFiles”函数(这两个函数的内容完全相同,只是类型不同)他们寻找的文件),然后“删除重复项”按钮调用“remove_invoices”函数。

很明显,前两个函数会打开一个 tkinter 文件对话框,您可以在其中分别找到 XML 和 LOG 文件。

找到文件后,路径存储在全局变量中,因此可用于在“remove_invoices”函数中工作。

例如,this 是“browseX”函数全部包含的内容,而全局变量是我试图摆脱的内容:

def browseLOGFiles():
logname = filedialog.askopenfilename(initialdir = "/Logs",
                                      title = "Select a File",
                                      filetypes = (("Text files",
                                                    "*.txt*"),
                                                   ("all files",
                                                    "*.*")))
global new_log_name
new_log_name = logname.split('/', -1)
logButton.configure(text=new_log_name[-1])

我当前的问题:

我正在尝试清理全局变量污染,所以我希望我的 remove_invoices 函数接收“browseX”函数的返回值。我尝试用函数本身替换全局变量(因为它now returns the path

def browseLOGFiles():
logname = filedialog.askopenfilename(initialdir = "/Logs",
                                      title = "Select a File",
                                      filetypes = (("Text files",
                                                    "*.txt*"),
                                                   ("all files",
                                                    "*.*")))
new_log_name = logname.split('/', -1)
logButton.configure(text=new_log_name[-1])
return new_log_name

而不是使用全局变量)。最终发生的事情是,当单击“删除重复项”按钮时,它没有使用函数的返回项,而是在 remove_invoices 函数中再次调用该函数,让您再次选择文件路径。

我应该如何重构我的代码,以便我可以:

  1. 防止全球可变污染
  2. 无需在remove_invoices函数中再次调用它们即可获得前面两个函数的结果:

功能:

def remove_invoices():
    try:
        error_file = open(browseLOGFiles(), "r") #This is closed later, I promise
    except Exception as e:
        if e == "name 'logname' is not defined":
            statusLabel.configure(text="Please upload a LOG(.txt) file.")
    try:
        global tree
        tree = ET.parse(browseXMLFiles)
        print(f'Opened {browseXMLFiles}. Parsing.')
    except:
        print(f"Can't find file the specified XML File. Was the filename typed exactly, including the extension?")
python python-3.x function variables global
© www.soinside.com 2019 - 2024. All rights reserved.