3 回答

TA贡献1852条经验 获得超7个赞
您可以使用循环和字符串插值将其减少为:
for key in ('name', 'type', 'of'):
if key not in item:
error = "no {} key found in definition".format(key)
return False, error, {}

TA贡献1796条经验 获得超10个赞
好吧,这段代码可以重构以避免像这样重复:
for part in ['name', 'type', 'of']:
if part not in item:
error = "no {} key found in definition".format(part)
return False, error, {}
不确定我是否可以添加很多关于 Python 中一般验证的最佳实践。我认为使用这样的通用结构几乎可以根据需要完成。

TA贡献1865条经验 获得超7个赞
如果您明确命名丢失的键而不是执行类似的操作
if "name" not in item or "type" not in item or "of" not in item:
return False, "key missing in definition", {}
你可能应该做对并遍历所有这些。调整 Dan D. 的解决方案:
error = ''
for key in ('name', 'type', 'of'):
if key not in item:
error += " no {} key found in definition".format(key)
if error != ''
return False, error, {}
或者类似的东西。如果缺少名称和类型怎么办?您只会在示例中看到缺少的名称。
添加回答
举报