首页 > 解决方案 > VS Code PyLint 错误 E0602(未定义变量)与 ProtoBuf 编译的 Python 结构

问题描述

我使用 Visual Studio 很长时间了,但它变得太复杂而无法维护。现在我尝试转向 VS Code,但它抛出了许多对我来说没有意义的 PyLint 错误消息(并且程序仍然按预期工作)。这些错误主要发生在从 GoogleProtoBuf 结构生成的 Python 代码中。

例如:

from lbsnstructure.lbsnstructure_pb2 import lbsnPost

def geoaccuracy_within_threshold(post_geoaccuracy, min_geoaccuracy):
    """Checks if geoaccuracy is within or below threshhold defined"""

    if min_geoaccuracy == lbsnPost.LATLNG:
        allowed_geoaccuracies = [lbsnPost.LATLNG]
    elif min_geoaccuracy == lbsnPost.PLACE:
        allowed_geoaccuracies = [lbsnPost.LATLNG, lbsnPost.PLACE]
    elif min_geoaccuracy == lbsnPost.CITY:
        allowed_geoaccuracies = [lbsnPost.LATLNG, lbsnPost.PLACE, lbsnPost.CITY]
    else:
        return True
    # check post geoaccuracy
    if post_geoaccuracy in allowed_geoaccuracies:
        return True
    else:
        return False

从 pyLint 引发错误消息 E0602:

未定义的变量 'lbsnPost' pylint (E0602)
lbsnPost: GeneratedProtocolMessageType

然而,谷歌明确指出这种形式的类型引用是正确的:

元类将枚举扩展为一组具有整数值的符号常量。因此,例如,常量 addressbook_pb2.Person.WORK 的值为 2。

我的代码中到处都是类似的错误(效果很好)。我怀疑这是我在错误的约定中写的东西,但不知何故仍然有效。但是什么是正确的约定?

屏幕截图 VSCode Pylint 错误 E0602

这个页面似乎讨论了同样的问题,但没有一个解决方案有效:
在 PyDev 中使用协议缓冲区时导入的未定义变量
也就是说,即使在这样做lbsnpost().LATLNG(实例化 protobuf 消息)时,我也会得到相同的未定义变量错误。

标签: visual-studio-codeprotocol-buffersconventionspylint

解决方案


我解决了我的问题。显然,pylint 对 protobuf 编译的 python 类有(有?)问题。有一个包可以解决这个问题。

  • 安装pylint-protobuf包 ( pip install pylint-protobuf)
  • 添加"python.linting.pylintArgs": ["--load-plugins", "pylint_protobuf"]到 VS Code 中的用户设置

没有错误!

有关更多信息,请参阅VS Code linting Docs


推荐阅读