2013-03-14 50 views
0

我知道這是在爲Java 8或9的管道,但我認爲必須有一種方法來做到這一點在Python中。例如說,我寫一個複雜的表達,不能被人打擾各級加上null檢查(下面的例子)如何做?沒有檢查

post_code = department.parent_department.get('sibling').employees.get('John').address.post_code 

我不想擔心幾個中間值是「無」。例如,如果parent_department沒有兄弟關鍵字,我想分流並將None分配給post_code。類似於

post_code = department?.parent_department?.get('sibling')?.employees?.get('John')?.address?.post_code 

這可以在Python 2.7.1中完成嗎?我知道這意味着在調試時會遇到更多麻煩,但假設我已經完成了所有的預檢,並且如果任何值爲空,則表示內部錯誤,所以如果我剛剛得到特定行失敗的錯誤跟蹤就足夠了。

這是一個更詳細的方法。我只需要一行代碼,不拋出隨機異常

def get_post_code(department): 
    if department is None: 
     return None 
    if department.parent_department is None: 
     return None 
    if department.parent_department.get('sibling') is None: 
     return None 
    ... more checks... 
    return post_code = department.parent_department.get('sibling').employees.get('John').address.post_code 
+1

它不清楚這些是什麼類型的對象。在字典中,'.get()'是一種方法,所以你可以用'.get('sibling')',* not * use indexing(.get ['sibling'])''來調用它,返回一個'KeyError'。如果該列表中的任何內容返回「None」或不存在,您已經會得到'AttributeError'或'KeyError'異常。 – 2013-03-14 13:59:51

+0

修正了(支架,假設語法是正確的,我只是不想要一個關鍵錯誤或屬性錯誤或一個空錯誤。我基本上希望post_code爲null,如果任何內部結構不是我所期望的 – 2013-03-14 14:01:33

回答

2

如果你想post_codeNone然後試圖訪問不存在的項目趕上拋出的異常:

try: 
    post_code = department.parent_department.get('sibling').employees.get('John').address.post_code 
except (AttributeError, KeyError): 
    post_code = None