我在撰寫 Python 代碼時遇到了一個相當哲學的問題。通常,使用盡可能多的try-except-else塊來處理所有可預期的情況被認為是一種很好的風格。但我發現這種方法有時會導致不必要的多級縮進,這使得很難將行數保持在 80 以下,并暗示代碼中不存在層次結構。我覺得我缺少某種 “GOTO”陳述句或類似的跳轉來應對這個問題。因此,我想知道我是否缺少一些編碼風格、Python 陳述句或模式來改進我的 Python 代碼。
我舉一個更具體的例子。讓我們認為我正在定義一個函式,并且我在一個回圈中,在那里各種事情可能會出錯。每件事都足以使回圈中的其余代碼可跳過,我通常以continue類似于以下方式跳過這些代碼:
def mu_func()
failed = False
for i in range(100):
try:
pass
# we try something that might raise an exception
except:
print("something went wrong by reason #1")
failed = True
continue
try:
pass
# we try something that might raise an exception
except:
print("something went wrong by reason #2")
failed = True
continue
try:
pass
# we try something that might raise an exception
except:
print("something went wrong by reason #3")
failed = True
# some cleanup code at the end of the function
# that depends on the errors raised
return failed
這里要注意的重要一點是,由于我們處于回圈中,如果引發任何例外,該continue陳述句使我不必使用else陳述句跳過其余代碼。因此,縮進級別不會繼續增長。另請注意,我不能只是退出例外處理,因為我需要在從函式回傳之前進行一些清理。
現在注意當我們不在回圈中時會發生什么:
def mu_func()
failed = False
try:
pass
# we try something that might raise an exception
except:
print("something went wrong by reason #1")
failed = True
else:
try:
pass
# we try something that might raise an exception
except:
print("something went wrong by reason #2")
failed = True
else:
try:
pass
# we try something that might raise an exception
except:
print("something went wrong by reason #3")
failed = True
# some cleanup code at the end of the function
# that depends on the errors raised
return failed
?See the difference? If want to skip the rest of the code after any exception has been raised, I have to put inside an else statement everything below, which trivially increases a level of indent from that point on. This not only leads to annoying code where it is difficult to to keep the line count below 80 characters. The worst aspect is that these nested try-except-else blocks suggest some sort of hierarchy in the code, which is artificial. All exceptions are equally important. This can be easily appreciated in the first example where the order of the try-except blocks could be nicely exchanged without touching the indent and without affecting the functionality.
Is there a Python statement, or pattern, that allows me to skip the rest of the code once an exception is handled, that precludes me from having to add more and more indent levels? Am I misusing the else statement? I'm tempted to put everything within a trivial 1-iteration loop so I have access to the continue statement to perform the jump to the end of block statement that I'm missing.
uj5u.com熱心網友回復:
一種方法可能是用try-except塊包裝 for 回圈:
def mu_func():
try:
for i in range(100):
# we try something that might raise an exception
action_1()
print("action #1 succeeds")
action_2()
print("action #2 succeeds")
action_3()
print("action #3 succeeds")
except:
print("something went wrong!")
failed = True
else:
failed = False
return failed
如果你的 for 回圈中有其他邏輯,我建議只包裝可能引發例外的邏輯:
def mu_func():
for i in range(100):
try:
# we try something that might raise an exception
action_1()
print("action #1 succeeds")
action_2()
print("action #2 succeeds")
action_3()
print("action #3 succeeds")
except:
print("something went wrong!")
failed = True
break
# here we might do other stuff in the loop
...
else:
failed = False
return failed
uj5u.com熱心網友回復:
怎么用:
def mu_func()
failed = False
try:
pass
# we try something that might raise an exception
except ExceptionClass1():
print("something went wrong by reason #1")
failed = True
except ExceptionClass2():
print("something went wrong by reason #2")
failed = True
except ExceptionClass3():
print("something went wrong by reason #3")
failed = True
except ExceptionClass4():
print("something went wrong by reason #4")
failed = True
return failed
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/337924.html
