Protocol Buffers
suggest changeProtocol Buffers (Protobuf) is Google's language-neutral, platform-neutral binary serialization format. Compared to text formats like JSON or XML, Protobuf payloads are significantly smaller, faster to serialize/deserialize, and strictly typed via predefined .proto schema files.
1. Installation
Install the Python runtime library:
pip install protobuf
To compile schema files (.proto), you also need the protoc compiler installed on your system (e.g., via brew install protobuf, apt install protobuf-compiler, or downloaded from GitHub releases).
2. Defining a .proto Schema
Create a schema file named person.proto:
syntax = "proto3";
package example;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
string number = 1;
PhoneType type = 2;
}
message Person {
int32 id = 1;
string name = 2;
string email = 3;
repeated PhoneNumber phones = 4; // Repeated field represents a list
map<string, string> attributes = 5;
}
3. Compiling the Schema
Generate the Python code using protoc:
protoc --python_out=. person.proto
This generates person_pb2.py containing message classes and descriptors.
4. Creating and Populating Messages
Import the generated module and build message objects:
import person_pb2
# Instantiate a Person message
person = person_pb2.Person(
id=101,
name="Jane Doe",
email="jane.doe@example.com"
)
# Populate repeated composite fields using add()
phone1 = person.phones.add()
phone1.number = "+1-555-0100"
phone1.type = person_pb2.PhoneType.MOBILE
phone2 = person.phones.add(
number="+1-555-0199",
type=person_pb2.PhoneType.WORK
)
# Populate map fields
person.attributes["department"] = "Engineering"
person.attributes["role"] = "Architect"
print(person.name)
print(f"Total phones: {len(person.phones)}")
5. Binary Serialization and Deserialization
Serializing to Binary
Use SerializeToString() to convert the protobuf message into a compact binary byte string:
binary_data = person.SerializeToString()
print(f"Serialized size: {len(binary_data)} bytes")
# Write to disk
with open("person.bin", "wb") as f:
f.write(binary_data)
Deserializing from Binary
Use ParseFromString() to populate a blank message instance:
from google.protobuf.message import DecodeError
import person_pb2
# Read binary data
with open("person.bin", "rb") as f:
raw_bytes = f.read()
new_person = person_pb2.Person()
try:
new_person.ParseFromString(raw_bytes)
print(f"Loaded Person: {new_person.name} (ID: {new_person.id})")
for phone in new_person.phones:
print(f" Phone: {phone.number} [{person_pb2.PhoneType.Name(phone.type)}]")
except DecodeError as e:
print(f"Failed to parse binary protobuf: {e}")
6. Converting Between Protobuf and JSON / Dict
Google provides google.protobuf.json_format for converting between protobuf messages and JSON or Python dictionaries:
from google.protobuf.json_format import MessageToJson, MessageToDict, Parse
# Convert message to JSON string
json_str = MessageToJson(person, preserving_proto_field_name=True)
print(json_str)
# Convert message to standard Python dict
person_dict = MessageToDict(person)
print(person_dict["name"])
# Parse JSON string back into a protobuf message
json_input = '{"id": 202, "name": "Alex Smith", "email": "alex@example.com"}'
parsed_person = person_pb2.Person()
Parse(json_input, parsed_person)
print(parsed_person.id) # => 202
7. Checking and Clearing Fields
In proto3, scalar fields have default values (e.g. 0 for numbers, "" for strings).
person = person_pb2.Person(id=1, name="Alice")
# Check if a message or repeated field is set / has entries
print(len(person.phones) > 0) # False
# Clear a specific field back to its default value
person.ClearField("name")
print(person.name) # => ""
# Clear all fields in the entire message
person.Clear()