python-3.x - 使用带有布尔文字错误的身份比较
问题描述
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”,则将被阻止。
解决方案
一种更简单的方法可能是使用dict.get(key, default)
, 和or
,这将导致一个虚假值成为您选择的另一个值:
attr_value = kwargs.get(attr, None) or None
推荐阅读
- javascript - Angularjs拆分数组
- google-analytics - 使用 MCC 帐户管理 Google Analytics(分析)帐户
- javascript - 使用查询参数提交表单
- spring - 使用带有中心化配置服务器的 keycloak 保护微服务中的服务
- html - 仅当页面足够小时才使页脚粘在底部
- aem - 如何只调用一次吊索模型
- sql - 带 2 个参数的 RTRIM
- cucumber - Cucumber: Running features parallely in 4.2
- xcode - Xcode 无法构建:“无法解析构建文件:XCBCore.BuildFile”
- windows - How to install OpenCV with minGW on an offline machine?