Undefined variable from import when using protocol

2019-06-21 03:44发布

问题:

I've got a PyDev project that uses protocol buffers. The protocol buffer files are located in a zip file generated by the protoc compiler. Everything works when I run the program, however PyDev reports "Undefined variable from import" for every enumeration constant. So for example:

import model_pb2

value = model_pb2.Expression(type = model_pb2.Expression.PARAMETER)

It reports the enum constant "PARAMETER" as being an undefined variable. There are several dozen similar errors in my program, and I'd like to fix them "properly" (i.e. not simply suppressing the warning.)

回答1:

I found that using for builtins as can work, but only if all the proto files are in a separate located in an external library (see http://pydev.org/manual_101_project_conf2.html).

This should work:

  1. Move (or unzip) the compiled proto files including model_pb2.py into a directory outside the pydev project.
  2. Add an empty __init__.py file to the same directory as model_pb2.py to ensure it can be imported as a library.
  3. In eclipse, go to Windows -> Preferences -> pydev -> Interpreter
  4. Add the directory with model_pb2.py to the Libraries.
  5. Add model_pb2 to the forced buildins.

If you're not addicted to autocomplete, you may using ctrl+1 to ignoring these errors instead as described in this answer. This was tested with Eclipse Kepler and pydev 2.8.



回答2:

Have you tried adding "model_pb2" to your forced builtins? See: http://pydev.org/manual_101_project_conf2.html for details.



回答3:

I encountered this issue with protobuf 2.6.1 and PyDev 4.5.5. I tried the suggestions above both none of them helped in my case. What ended up getting rid of the 'undefined variable' errors when using protobuf enums was simple:

Access the enum on an instantiated protobuf object rather than on the protobuf module.

I'm not sure if this could be applied to the OP's use case, but in mine it was as easy as:

from myprotobuf_module import SomeProtobufMessage

some_protobuf_object = SomeProtobufMessage()
some_enum = some_protobuf_object.SOME_ENUM