Protocol Buffers (protobuf) for Python

7.34.1 · active · verified Fri Mar 27

Google's language-neutral, platform-neutral mechanism for serializing structured data. You define message schemas in .proto files, compile them with protoc into _pb2.py modules, and use the runtime library (google.protobuf.*) to serialize, deserialize, and manipulate messages. Currently at version 7.34.1 (Python major version bumped from 6.x to 7.x in the 7.34.0 release). Releases follow a quarterly cadence; breaking major-version bumps are targeted at Q1 of each year.

Warnings

Install

Imports

Quickstart

Serialize and deserialize a message using a well-known type (no custom .proto compilation required). Demonstrates SerializeToString / ParseFromString and JSON round-trip.

# pip install protobuf
# No custom .proto needed for this example — uses the built-in Timestamp well-known type.

from google.protobuf.timestamp_pb2 import Timestamp
from google.protobuf import json_format
import time

# --- Create and populate a message ---
ts = Timestamp()
ts.GetCurrentTime()          # sets seconds + nanos to now

# --- Binary serialization round-trip ---
binary = ts.SerializeToString()
ts2 = Timestamp()
ts2.ParseFromString(binary)  # returns number of bytes consumed
assert ts == ts2, "Round-trip failed"

# --- JSON serialization ---
json_str = json_format.MessageToJson(ts)
print("JSON:", json_str)

ts3 = json_format.Parse(json_str, Timestamp())
assert ts == ts3, "JSON round-trip failed"
print("All assertions passed.")

# --- Typical workflow with a custom proto ---
# 1. Write my_message.proto:
#      syntax = "proto3";
#      message Person { string name = 1; int32 id = 2; }
# 2. Compile:
#      protoc --python_out=. my_message.proto
# 3. Use generated code:
#      from my_message_pb2 import Person
#      p = Person(name='Alice', id=42)
#      data = p.SerializeToString()
#      p2 = Person()
#      p2.ParseFromString(data)

view raw JSON →