2010-06-24 64 views
6

我有一大堆的代碼看起來與此類似:有沒有一種很好的方式來處理Python中的異常?

   try: 
        auth = page.ItemAttributes.Author 
       except: 
         try: 
          auth = page.ItemAttributes.Creator 
         except: 
           auth = None 

有沒有寫出來這個邏輯更好的方式?這使我的代碼非常痛苦,閱讀。我以爲try..finally會的工作,但我認爲錯

回答

11

您可以使用hasattr避免在try/except塊:

auth = None 
for attrname in ['Author', 'Creator']: 
    if hasattr(page.ItemAttributes, attrname): 
     auth = getattr(page.ItemAttributes, attrname) 
     break 

的另一種方法來寫上面是使用的else條款一個Python for循環:

for attrname in ['Author', 'Creator']: 
    if hasattr(page.ItemAttributes, attrname): 
     auth = getattr(page.ItemAttributes, attrname) 
     break 
else: 
    auth = None 
+0

@馬克乾淨的代碼 – systempuntoout 2010-06-24 22:13:01

+0

+1它不僅是清潔的,但它不需要完全處理異常。 – BoltClock 2010-06-24 22:13:22

+0

@馬克懷疑..你怎麼能確定該頁面有ItemAttributes?它可能是None。 – systempuntoout 2010-06-24 22:17:12

3

這使我的代碼,真的很痛苦閱讀

無論你做什麼,都不要捕獲通配符。 except:是pythonic方式說:Hey, all exceptions are equal, I want every single error in my try block to end up here, I don't care if I catch an AttributeError or a WorldGotFuckedUpException。在你的情況下,except AttributeError是更好,更容易閱讀。

這只是一個側面說明。馬克的答案顯示了最好的辦法,恕我直言。

+0

哈哈,注意到......我只是懶惰,並且在我會記住捕捉特定的例外之前,有必要有一個非常可怕的經歷。 – xporter 2010-06-24 22:20:59

2

@馬克Byers公司的回答是更靈活,但如果你想要一個班輪

auth = getattr(page.ItemAttributes, 'Author', None) or getattr(page.ItemAttributes, 'Creator', None) 
+4

這不完全一樣 - 'page.ItemAttributes.Author'可能是'None'。原始代碼允許這種情況。 – 2010-06-24 22:19:59

相關問題