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.
pip install protobufVerified import paths — ran on the pinned version, not inferred.
Serialize and deserialize a message using a well-known type (no custom .proto compilation required). Demonstrates SerializeToString / ParseFromString and JSON round-trip.
Upgrade to >=7.34.1. Replace boolean literals with int values when assigning to int/enum fields (e.g. use 1 instead of True). Remove any use of float_precision= in json_format.MessageToJson() and float_format=/double_format= in text_format calls.
Always regenerate _pb2.py files with the same protoc version as your installed runtime. Pin grpcio-tools and protobuf together in requirements. Generated code for major version V works only with runtime major versions V and V+1.
Set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=cpp and install the Python/C++ extension if you need Python↔C++ message sharing, or upgrade dependent libraries (e.g. TF >=2.12) that have been updated to use upb.
Replace msg.UnknownFields() with: from google.protobuf import unknown_fields; unknown_fields.UnknownFieldSet(msg)
Use 'key in msg.map_field' to check existence before accessing. Use msg.map_field.get(key) where available, or msg.map_field.GetOrCreate(key) for message-typed maps.
Pass --proto_path rooted at the common ancestor of all .proto files. Ensure generated _pb2.py files are on PYTHONPATH. Well-known google/* protos must always be imported as 'google/protobuf/...' in .proto files.
Compose rather than inherit: hold a proto message as a field, or use helper functions. For custom serialization logic, wrap the message in a plain Python class.