VS Code PyLint 错误 E0602(未定义的变量)与 ProtoBuf 编译的 Python 结构

2024-01-12

我使用 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:生成的协议消息类型

然而,谷歌明确指出 https://developers.google.com/protocol-buffers/docs/pythontutorial这种形式的类型引用是正确的:

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

我的代码中到处都是类似的错误(工作正常)。我怀疑这是我按照错误的约定编写的内容,但不知何故仍然有效。但什么是正确的约定呢?

此页面似乎讨论了同一问题,但没有一个解决方案有效:
在 PyDev 中使用协议缓冲区时导入未定义的变量 https://stackoverflow.com/questions/11278062/undefined-variable-from-import-when-using-protocol-buffers-in-pydev
也就是说,即使在做lbsnpost().LATLNG(实例化 protobuf 消息),我得到相同的未定义变量错误。


我解决了我的问题。显然 https://github.com/PyCQA/pylint/issues/1165, pylint 对 protobuf 编译的 python 类有(有?)问题。有一个包可用的 https://pypi.org/project/pylint-protobuf/这解决了这个问题。

  • 已安装pylint-protobuf https://pypi.org/project/pylint-protobuf/包裹 (pip install pylint-protobuf)
  • added "python.linting.pylintArgs": ["--load-plugins", "pylint_protobuf"]VS Code 中的用户设置

没有错误!

欲了解更多信息,请参阅VS Code linting 文档 https://code.visualstudio.com/docs/python/linting#_commandline-arguments-and-configuration-files

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

VS Code PyLint 错误 E0602(未定义的变量)与 ProtoBuf 编译的 Python 结构 的相关文章

随机推荐