首页 > 解决方案 > 使用带有布尔文字错误的身份比较

问题描述

cmd =[]
def SetOSPFInterface(**kwargs):
    attribute_map = {
        'priority': 'priority',
        'passive': 'passive',
        'interface_type': 'interface-type',
        'metric': 'metric',
    }
    for attr, cfg_expr in attribute_map.items():
        attr_value = kwargs.get(attr) if kwargs.get(attr) is not False else None
        print(attr_value, attr)
        if attr_value is not None:
            if isinstance(attr_value, bool):
                attr_expr = ''
            else:
                attr_expr = ' %s' % attr_value
            cmd.append('set %s%s' % (cfg_expr, attr_expr))

    return cmd
print(SetOSPFInterface(priority=0))

我正在尝试将“优先级值设置为 0”,当前的实现正在抛出布尔文字错误(使用与布尔文字错误的身份比较,这是一个 python lint 错误。这说明使用 'is' 不是好习惯,'不是'带有布尔值)。因此,如果我将条件更改为attr_value = kwargs.get(attr) if kwargs.get(attr) and isinstance(kwargs.get(attr), bool) else None优先值“0”,则将被阻止。

标签: python-3.xautomationnetwork-programming

解决方案


一种更简单的方法可能是使用dict.get(key, default), 和or,这将导致一个虚假值成为您选择的另一个值:

attr_value = kwargs.get(attr, None) or None

推荐阅读