Pylint - 如何修复ID:maybe-no-member错误?

4 投票
1 回答
1871 浏览
提问于 2025-04-18 00:35

我刚接触pylint。最近我用pylint检查了一段代码,结果在尝试遍历一个字典时出现了错误:

"ID:maybe-no-member Instance of 'bool' has no 'iteritems' member (but some types could not be 
 inferred)"

这是一个Flask应用,我通过AJAX把一个json编码的字典传到'/my_endpoint/'。接下来我需要遍历这个字典并进行一些操作。

@app.route('/my_endpoint/')
def my_endpoint():
    """My Description"""
    try:
        my_params = json.loads(request.args.get('names'))
    except TypeError:
        my_params = None

    if my_params is not None:
        for key,value in my_params.iteritems(): # error occurs here
            ...

我尝试在网上搜索这个错误,但没有找到任何关于这个错误的解释或者解决办法。谢谢!

1 个回答

3

我猜测(这只是个大胆的猜测),Pylint 抱怨的原因是因为 json.loads 这个函数在解码像 "false" 这样的字符串时,可能会返回一个布尔值(true 或 false)。而这个布尔值实际上是没有名为 iteritems 的方法的。

不过,字符串、列表或数字也都没有这个方法,所以我不明白为什么它偏偏挑布尔值的毛病。也许是因为在所有可能的类型中,布尔值的字母顺序排在最前面。

如果我明确地检查一下 isinstance(my_params, dict),这样会让它满意吗?

撰写回答