Python Protoletariat

3.3.10 · active · verified Sat Apr 11

Protoletariat is a Python utility designed to address the long-standing issue of absolute imports in Python code generated by the official Protocol Buffers compiler (`protoc`). It acts as a post-processing step, rewriting these problematic absolute imports into correct relative imports, enabling smoother integration of generated protobuf code within Python packages. The library is actively maintained with frequent dependency updates.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the core workflow of `protoletariat`. It involves defining two `.proto` files with a dependency, generating Python stubs using `protoc`, and then using the `protol` command-line tool to convert the absolute imports generated by `protoc` into relative imports for proper Python package structure. The `--create-package` flag creates an `__init__.py` file if it doesn't exist, making the output directory a valid Python package.

mkdir -p out protos
cat <<EOF > protos/thing1.proto
syntax = "proto3";
import "thing2.proto";
package things;
message Thing1 { Thing2 thing2 = 1; }
EOF
cat <<EOF > protos/thing2.proto
syntax = "proto3";
package things;
message Thing2 { string data = 1; }
EOF

# Step 1: Generate Python code with protoc
protoc \
  --python_out=out \
  --proto_path=protos protos/thing1.proto protos/thing2.proto

echo "\n--- Before protoletariat ---"
cat out/thing1_pb2.py | grep 'import thing2_pb2'

# Step 2: Fix imports with protol
protol \
  --create-package \
  --in-place \
  --python-out out \
  --proto-path=protos protos/thing1.proto protos/thing2.proto

echo "\n--- After protoletariat ---"
cat out/thing1_pb2.py | grep 'import thing2_pb2'

# Expected output shows 'from . import thing2_pb2'

view raw JSON →