7.35-dev) supports three implementation backends and generates _pb2.py modules that you import directly.
Installation
Install the protobuf package
upb, a C extension built on the upb library that delivers the best performance.Install protoc
Download the prebuilt
protoc binary for your platform from the releases page and add it to your $PATH.Generating code
Runprotoc with --python_out to generate a _pb2.py module:
addressbook_pb2.py. To also generate a type stub (.pyi) for IDE support:
_pb2.pyi stub file is human-readable and useful for IDE autocompletion. The _pb2.py file itself is optimized for fast loading and is not intended to be read directly.
Working with messages
Import the generated module and create messages as plain Python objects:Serializing and parsing
Full example: add_person.py
This example reads an address book from disk, prompts for a new person, and writes it back:Implementation backends
The Python runtime automatically selects the best available backend. You can override this with thePROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION environment variable:
| Backend | Description | Performance |
|---|---|---|
upb | C extension built on the upb library. Default since 4.21.0. | Best |
cpp | Wraps the C++ protobuf library. Deprecated; not in PyPI packages. | Good |
python | Pure Python. No C extension required. | Slowest |
The
cpp backend is no longer distributed via PyPI. It exists only for legacy use cases requiring zero-copy message sharing between Python and C++.Descriptor and reflection APIs
Thegoogle.protobuf.descriptor module exposes the full descriptor for each message. This is useful for generic serialization code, validation frameworks, and schema inspection:
Key API reference
Message
All generated classes are subclasses of
google.protobuf.message.Message. Fields are set as attributes. Repeated fields behave like Python lists. Map fields behave like Python dicts.Serialization
SerializeToString() — returns bytes.
ParseFromString(data) — parses bytes in place.
MergeFromString(data) — merges bytes into an existing message.JSON
google.protobuf.json_format.MessageToJson(message) and JsonFormat.Parse(json_string, message) for JSON conversion.Descriptors
Message.DESCRIPTOR — access the Descriptor object. Use descriptor_pool and message_factory for dynamic message creation.