最低工作代码:
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。
我认为也许“终于”和“其他”是答案,但最终发生在 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)