Search code examples
visual-studio-codeprotocol-buffersconventionspylint

VS Code PyLint Error E0602 (undefined variable) with ProtoBuf compiled Python Structure


I was using Visual Studio for a long time, but it was becoming too complicated to maintain. Now I tried to move to VS Code, but it throws a number of PyLint error messages that don't make sense to me (and the program still works as expected). These errors happen primarily with Python code generated from a GoogleProtoBuf structure.

For example:

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

Throws error message E0602 from pyLint:

Undefined variable 'lbsnPost' pylint (E0602)
lbsnPost: GeneratedProtocolMessageType

However, Google explicitly states that this form of type-referencing is correct:

Enums are expanded by the metaclass into a set of symbolic constants with integer values. So, for example, the constant addressbook_pb2.Person.WORK has the value 2.

I get similar errors all over my code (that works fine). I suspect that this is something that I have written in the wrong convention, but somehow still works. But what is the right convention?

Screenshot VSCode Pylint Error E0602

This page seems to discuss the same issue, but none of the solutions work:
Undefined variable from import when using protocol buffers in PyDev
that is, even when doing lbsnpost().LATLNG (instantiating the protobuf message), I get the same undefined variable error.


Solution

  • I solved my problem. Apparently, pylint has (had?) problems with protobuf compiled python classes. There's a package available that solves this issue.

    • installed pylint-protobuf package (pip install pylint-protobuf)
    • added "python.linting.pylintArgs": ["--load-plugins", "pylint_protobuf"] to User Settings in VS Code

    No errors!

    For more information, see the VS Code linting Docs