Protocol Buffers for the Rest of Us


protoletariat has one goal: fixing the broken imports for the Python code generated by protoc.


Here’s an example of how to use the tool, called protol:

  1. Create a few protobuf files

// thing1.proto
syntax = "proto3";

import "thing2.proto";

package things;

message Thing1 {
  Thing2 thing2 = 1;

// thing2.proto
syntax = "proto3";

package things;

message Thing2 {
  string data = 1;
  1. Run protoc on those files

$ mkdir out
$ protoc --python_out=out --proto_path=directory/containing/protos thing1.proto thing2.proto
  1. Run protol on the generated code

$ protol --create-init --overwrite -g out --proto-path=directory/containing/protos thing1.proto thing2.proto

The out/ file should show a diff containing at least these lines:

-import thing2_pb2 as thing2__pb2
+from . import thing2_pb2 as thing2__pb2

How it works

At a high level, protoletariat converts absolute imports to relative imports.

However, it doesn’t just convert any absolute import to a relative import.

The protol tool will only convert imports that were generated from .proto files. It does this by inspecting FileDescriptorProtos from the protobuf files.

The core mechanism is implemented using a simplified form of pattern matching, that looks at the Python AST, and if an import pattern is matched and corresponding rewrite rule is fired.


$ protol --help
Usage: protol [OPTIONS] PROTO_FILES...

  Rewrite protoc-generated imports for use by the proletariat.

  -g, --generated-python-dir DIRECTORY
                                  Directory containing generated Python code
  -p, --proto-path DIRECTORY      Protobuf file search path(s). Accepts
                                  multiple values.  [required]
  --overwrite / --no-overwrite    Overwrite all generated Python files with
                                  modified imports
  --create-init / --dont-create-init
                                  Create an file under the
                                  `generated-python-dir` directory
  --help                          Show this message and exit.


View Github