【发布时间】:2021-07-15 15:46:24
【问题描述】:
最低工作代码:
step1_failed = False
try:
print("step #1")
except:
step1_failed = True
print("step #2") # always appening after step #1 but before step #3 regardless of if step #1 failed or not
if not step1_failed:
print("step #3") # only if step #1 execute without error
我的问题是:有没有更好的我看不到的方法?
最好没有像 step1_failed 这样的虚拟变量。
我认为也许“finally”和“else”是答案,但最终发生在 else 之后,我需要在 else 语句之前做一些事情。
这个用例是针对 PyQt5,我想断开一个信号并在做某事后重新连接它以避免不必要的递归。 但是我需要重新连接它,前提是它最初是连接的。
这是我的 PyQt5 代码,以了解我为什么需要它:
def somefunction():
connected_at_first = True # assuming it was connected
try:
lineedit1.textChanged.disconnect(somefunction) # throw a TypeError if it is not connected
except TypeError:
connected_at_first = False # happen only if lineedit1 wasn't connected
lineedit1.setText("always happening !")
# reconnecting lineedit1 if it was connected at the beginning
if connected_at_first:
lineedit1.textChanged.connect(somefunction)
【问题讨论】:
-
我不能把第 2 步放在前面的最后一行,除非因为第 1 步失败,第 2 步将不会执行。无论第 1 步如何,我都需要始终执行第 2 步。
-
@not_speshal OP 说第 2 步必须在第 3 步之前进行
-
stackoverflow.com/q/21586643/1126841 是相关的,如果不是重复的话。
-
我在发布这个问题之前找到了 stackoverflow.com/q/21586643/1126841,但这并不是我真正想要的。这个问题更多的是关于如何将连接从一个更改为另一个,而不是在中间做某事。
标签: python pyqt5 try-except