如何在if / else语句中避免重复代码?

时间:2017-10-16 15:11:59

标签: python algorithm python-3.x

我在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)

有没有办法做一次这个逻辑?

2 个答案:

答案 0 :(得分:2)

你似乎在每一个条件下都做等待线,只是你的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)

答案 1 :(得分:1)

放弃字典。仅在外部if结束后调用该方法。通过翻录所有分支共有的表达式来简化块。 像这样:

if alert.get('comment_time_created') is not None:       
    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:
        comment_time_created = current_comment_time

await self._db_alert.update_alert(alert['alert_id'], is_comment_visible = 1, comment_time_created = comment_time_created)