[英]How to not return two different types from func?
I have the following method: 我有以下方法:
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
That's how I use it: 这就是我的用法:
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
I'm new in python. 我是python的新手。 I don't know is it good to return in one method tuple
- True, comm.get('email')
and just one value - False
. 我不知道它的好处是在一个方法返回tuple
- True, comm.get('email')
只是一个值- False
。
Is there any way to improve algorithm and rewrite it in the more pythonic way (I mean rewrite loop iteration)? 有什么方法可以改善算法并以更pythonic的方式重写它(我的意思是重写循环迭代)?
Provided that comm.get('email')
can not be None
itself, you could just return the e-mail of the pending comment, if any, or None
otherwise. 如果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
And then check like this: 然后像这样检查:
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
You could also rewrite this using next
, but whether that's better might be a matter of taste: 您也可以使用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)
It is perfectly fine to return a tuple
from a method. 从方法返回tuple
是完全可以的。
If you don't like the fact you return only False
you can always return False, None
如果你不喜欢的事实,你只返回False
,你可以随时返回False, None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.