我在 if/else 语句中有两个完全相同的逻辑:
if alert.get('comment_time_created') is None:
here-> args = {'is_comment_visible': 1, 'comment_time_created': current_comment_time}
await self._db_alert.update_alert(alert['alert_id'], **args)
else:
first_comment_time_creation = datetime.strptime(alert['comment_time_created'], '%Y-%m-%dT%H:%M:%SZ')
current_comment_time = datetime.strptime(current_comment_time, '%Y-%m-%dT%H:%M:%SZ')
if current_comment_time > first_comment_time_creation:
await self._db_alert.update_alert(alert['alert_id'], is_comment_visible=1)
else:
here-> args = {'is_comment_visible': 1, 'comment_time_created': current_comment_time}
await self._db_alert.update_alert(alert['alert_id'], **args)
有没有办法把这个逻辑做一次?
最佳答案
您似乎在每种情况下都执行 await 行,只是您的 kwargs 在您没有 comment_time_created
arg 的地方改变了一个特定条件。这可以简化为:
args = {'is_comment_visible': 1}
if alert.get('comment_time_created') is None:
args['comment_time_created'] = current_comment_time
else:
first_comment_time_creation = datetime.strptime(alert['comment_time_created'], '%Y-%m-%dT%H:%M:%SZ')
current_comment_time = datetime.strptime(current_comment_time, '%Y-%m-%dT%H:%M:%SZ')
if current_comment_time <= first_comment_time_creation:
args['comment_time_created']= current_comment_time
await self._db_alert.update_alert(alert['alert_id'], **args)
关于python - 如何避免 if/else 语句中的重复代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46773511/