Skip to content

Python Protobuf interface

Stephen Fegan edited this page Mar 7, 2016 · 33 revisions

Package

Enumerations

An enumeration such as

enum EnumType {
  UNKNOWN = 0,
  STARTED = 1,
  RUNNING = 2
};

will produce functions to

  • check whether an integer value represents a valid enumerated value

  • convert integer values to the stringified name of the enumerated value

  • and

    bool = EnumType_IsValid(value) string = EnumType_Name(value) [bool, value] = EnumType_Parse(string)

Where bool is a Python boolean value (True or False), value is an Python integer variable and string is a Python string variable.

EnumType_MIN = UNKNOWN;
EnumType EnumType_MAX = RUNNING;

For the example given above we would have,

>>> print(EnumType_MIN)
0
>>> print(EnumType_MAX)
2
>>> print(EnumType_IsValid(1))
True
>>> print(EnumType_IsValid(3))
False
>>> print(EnumType_Name(1))
STARTED
>>> print(EnumType_Name(3))

>>> print(EnumType_Parse('RUNNING'))
[True, 2]
>>> print(EnumType_Parse('BLAHBLAHBLAH'))
[False, 0]

Messages

Message fields

Singular Numeric, String and Bytes Fields

Given a message m, a field such as

int32 f = 1;

will produce the following Python member functions to get, set and clear the field f:

value = m.f()
m.set_f(value)
m.clear_f()

where value is a Python variable. This applies to protobuf types bool, int32, uint32, int64, uint64, float, double, string and bytes. Protobuf numeric types are converted to equivalent Python types, string to a Python UTF string and byte to Python byte string.

Singular Enum Fields

An enum field of type EnumType, such as

EnumType e = 1;

produces Python member functions to get, set, and clear f,

value = m.f()
m.set_f(value)
m.clear_f()

In this case value will be an integer type.

Singular Embedded Message Fields