2017-10-06 56 views
2

我有以下方法:如何不從func返回兩種不同的類型?

async def check_for_pending_status(self, alert_id): 
    alert_comments = await get_comments(alert_id) 
    for comm in alert_comments: 
     if comm['status'] == COMMENT_STATUS.PENDING.value: 
      return True, comm.get('email') 
    return False 

這就是我如何使用它:

is_pending_exists, email = await self.check_for_pending_status(comment.alert_id) 
if is_pending_exists: 
    comment['status'] = COMMENT_STATUS.PENDING 
    if email is not None: 
     comment['email'] = email 

我在蟒蛇新。我不知道用一種方法返回tuple - True, comm.get('email')並且只有一個值 - False

有什麼辦法來改進算法,並以更pythonic的方式重寫它(我的意思是重寫循環迭代)?

+2

爲什麼不'回comm.get(「email」)或'return None'? 「真/假」有點多餘。或者'comm.get(「email」)'是'None'? (從第二個'if'看起來好像可以) –

+0

@tobias_k是的,我可以'返回comm.get(「email」)'。你能把它寫成答案,我可以接受嗎? – petrush

+0

好的做法是**始終從函數**返回相同的類型(在所有退出路徑中)。在這種情況下,你會希望總是返回一個由'(bool,email)'對組成的元組。 – Darthfett

回答

3

只要comm.get('email')可以None本身,你可以只返回待定評論的電子郵件,如果任何或None

async def check_for_pending_status(self, alert_id): 
    alert_comments = await get_comments(alert_id) 
    for comm in alert_comments: 
     if comm['status'] == COMMENT_STATUS.PENDING.value: 
      return comm.get('email') 
    return None 

再檢查這樣的:

pending_email = await self.check_for_pending_status(comment.alert_id) 
if pending_email is not None: 
    comment['status'] = COMMENT_STATUS.PENDING 
    comment['email'] = email 

你也可以重寫這個使用next,但不管是更好的可能是口味的問題:

async def check_for_pending_status(self, alert_id): 
    alert_comments = await get_comments(alert_id) 
    return next((comm.get('email') for comm in alert_comments 
       if comm['status'] == COMMENT_STATUS.PENDING.value), 
       None) 
+0

'comm.get('email')'可以返回無 – petrush

+0

@petrush嗯,這就是爲什麼我在在發佈此答案之前發表評論...: -/ –

+0

@petrush如果電子郵件_can_爲「無」,那麼您確實不應該使用此功能,因爲您無法通過無電子郵件和非等待評論。 –

2

從方法返回tuple是完全正確的。

如果你不喜歡你只有False返回事實上,你可以隨時返回False, None

+1

我也是這樣,但我不會說「如果你不喜歡這個事實......」。 OP的原始代碼根本無法使用結果解包('is_pending_exists,email = await self.check_for ...') –