Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protocol Buffers in Python 3 - NotImplementedError

I am trying to use Google Protocol Buffers in a Python 3 project. However the generated python files do not want to cooperate with the google.protobuf library. Trying to use the protobuf objects results in a NotImplementedError.

My setup:

  • Python 3.4.1
  • protoc 2.5.0

The problem appears when using these libraries:

  • protobuf-py3 (https://pypi.python.org/pypi/protobuf-py3/2.5.1)
  • python3-protobuf (https://pypi.python.org/pypi/python3-protobuf/2.5.0)

Example:

from pb_test import test_pb2
pb_object = test_pb2.TestMsg()
pb_object.Clear()  # results in NotImplementedError

The fact that the same problem occurs when using two different libraries is a strong hint towards having an invalid test_pb2.py file. The 'unimplemented' methods are located in Message class, which is supposed to be overridden by metaclass. It seems that the metaclass is not applied at all.

The test.proto file:

message TestMsg {
  required int32 id = 1;
}

The file is compiled using this command:

eipifi@debvm:~/pb_test$ protoc --python_out=. test.proto

Any hints would be appreciated.

like image 548
Eipifi Avatar asked Oct 21 '22 04:10

Eipifi


1 Answers

Solved. In order to make the *_pb2.py files play well with the protobuf libraries in Python 3, the files need to be changed in a following way:

Original:

class TestMsg(_message.Message):
__metaclass__ = _reflection.GeneratedProtocolMessageType
DESCRIPTOR = _TESTMSG

Fixed:

class TestMsg(_message.Message, metaclass=_reflection.GeneratedProtocolMessageType):
DESCRIPTOR = _TESTMSG
like image 91
Eipifi Avatar answered Oct 22 '22 16:10

Eipifi