通过其他方法退出lambda表达式



我有一个程序,可以通过单击按钮启动数据类型转换。我正在为按钮命令使用lambda函数。在转换开始之前,一个方法会检查是否已选择输入。现在,如果还没有选择输入文件,我会在jupyter笔记本中收到一条错误消息,这不一定是个问题,因为数据类型转换无论如何都不应该开始。然而,我问自己是否有办法停止lambda函数的继续。我将添加我的代码片段,并进一步解释我的意思:

我的按钮命令:

self.program_start["command"]=lambda:[self.fileselectwarning(),self.writealldatafile(),self.writeselecteddata(),
self.inputliste.clear(),self.fileopeningcounter.set(0),
self.inputfilenamelist.clear()]

检查是否已选择输入/输出文件的方法:

def fileselectwarning(self):
stringliste=[self.fileopenname.get(),self.filesavename.get()]
if stringliste[0]=="" and not stringliste[1]=="":
self.messagebox1 = messagebox.showwarning("Missing Inputfile","No Inputfile selected, please select one and retry!")
elif not stringliste[0]=="" and stringliste[1]=="":
self.messagebox2 = messagebox.showwarning("Missing Outputfile","No Outputfilename selected, please select one and retry!")
elif stringliste[0]=="" and stringliste[1]=="":
self.messagebox3 = messagebox.showwarning("Missing Files","Neither Input nor Outputfile were selected, please select both and retry!")
elif not stringliste[0]=="" and not stringliste[1]=="":
ausfuehrenderdatenverarbeitung=self.zugriffaufdatenverarb()

因此,在我的方法fileselectwarning中,当一个输入和输出文件都被选中时,会调用另一个方法,开始部分转换。然后调用我的按钮的lambda函数中的所有其他方法,这些方法取决于通过我的"fileselectwarning"方法调用的方法中创建的列表。但是,如果输入或输出文件丢失,则lambda函数会继续,并且这些列表尚未创建,因此会产生错误。

要将其四舍五入,有没有办法阻止lambda函数继续运行并在"fileselectwarning"方法中实现它?

与其在lambda表达式中滥用列表构造函数来调用函数作为副作用,不如编写一个正则函数。

为了中止执行,可以使用fileselectwarning引发的自定义异常。这个功能本身也可以简化。

class MissingFiles(Exception):
pass
class ...:
def fileselectwarning(self):
infile, outfile = self.fileopenname.get(), self.filesavename.get()
if not infile and outfile:
raise MissingFiles("No Inputfile selected, please select one and retry!")
elif infile and not outfile:
raise MissingFiles("No Outputfilename selected, please select one and retry!")
elif not infile and not outfile:
raise MissingFiles("Neither Input nor Outputfile were selected, please select both and retry!")
else:
ausfuehrenderdatenverarbeitung=self.zugriffaufdatenverarb()
def start_command(self):
try:
self.fileselectwarning()
except MissingFiles as e:
self.messagebox1 = messagebox.showwarning("Missing files", str(e))
return
self.writealldatafile()
self.writeselecteddata()
self.inputliste.clear()
self.fileopeningcounter.set(0)
self.inputfilenamelist.clear()

然后在分配命令时,执行:

self.program_start["command"] = self.start_command

很明显,我无法对此进行测试,所以它可能无法立即运行,但它显示了总体思路。

最新更新