我有以下方法:如何不從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的方式重寫它(我的意思是重寫循環迭代)?
爲什麼不'回comm.get(「email」)或'return None'? 「真/假」有點多餘。或者'comm.get(「email」)'是'None'? (從第二個'if'看起來好像可以) –
@tobias_k是的,我可以'返回comm.get(「email」)'。你能把它寫成答案,我可以接受嗎? – petrush
好的做法是**始終從函數**返回相同的類型(在所有退出路徑中)。在這種情況下,你會希望總是返回一個由'(bool,email)'對組成的元組。 – Darthfett