| 1 |
Fields |
| 2 |
====== |
| 3 |
|
| 4 |
Fields are assigned using the :class:`~.Field` class, instantiated within a |
| 5 |
:class:`~.Message` declaration. |
| 6 |
|
| 7 |
Fields always have a type (either a primitive, a message, or an enum) and a |
| 8 |
``number``. |
| 9 |
|
| 10 |
.. code-block:: python |
| 11 |
|
| 12 |
import proto |
| 13 |
|
| 14 |
class Composer(proto.Message): |
| 15 |
given_name = proto.Field(proto.STRING, number=1) |
| 16 |
family_name = proto.Field(proto.STRING, number=2) |
| 17 |
|
| 18 |
class Song(proto.Message): |
| 19 |
composer = proto.Field(Composer, number=1) |
| 20 |
title = proto.Field(proto.STRING, number=2) |
| 21 |
lyrics = proto.Field(proto.STRING, number=3) |
| 22 |
year = proto.Field(proto.INT32, number=4) |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
For messages and enums, assign the message or enum class directly (as shown |
| 27 |
in the example above). |
| 28 |
|
| 29 |
.. note:: |
| 30 |
|
| 31 |
For messages declared in the same module, it is also possible to use a |
| 32 |
string with the message class' name *if* the class is not |
| 33 |
yet declared, which allows for declaring messages out of order or with |
| 34 |
circular references. |
| 35 |
|
| 36 |
Repeated fields |
| 37 |
--------------- |
| 38 |
|
| 39 |
Some fields are actually repeated fields. In protocol buffers, repeated fields |
| 40 |
are generally equivalent to typed lists. In protocol buffers, these are |
| 41 |
declared using the **repeated** keyword: |
| 42 |
|
| 43 |
.. code-block:: protobuf |
| 44 |
|
| 45 |
message Album { |
| 46 |
repeated Song songs = 1; |
| 47 |
string publisher = 2; |
| 48 |
} |
| 49 |
|
| 50 |
Declare them in Python using the :class:`~.RepeatedField` class: |
| 51 |
|
| 52 |
.. code-block:: python |
| 53 |
|
| 54 |
class Album(proto.Message): |
| 55 |
songs = proto.RepeatedField(Song, number=1) |
| 56 |
publisher = proto.Field(proto.STRING, number=2) |
| 57 |
|
| 58 |
|
| 59 |
.. note:: |
| 60 |
|
| 61 |
Elements **must** be appended individually for repeated fields of `struct.Value`. |
| 62 |
|
| 63 |
.. code-block:: python |
| 64 |
|
| 65 |
class Row(proto.Message): |
| 66 |
values = proto.RepeatedField(proto.MESSAGE, number=1, message=struct.Value,) |
| 67 |
|
| 68 |
>>> row = Row() |
| 69 |
>>> values = [struct_pb2.Value(string_value="hello")] |
| 70 |
>>> for v in values: |
| 71 |
>>> row.values.append(v) |
| 72 |
|
| 73 |
Direct assignment will result in an error. |
| 74 |
|
| 75 |
.. code-block:: python |
| 76 |
|
| 77 |
class Row(proto.Message): |
| 78 |
values = proto.RepeatedField(proto.MESSAGE, number=1, message=struct.Value,) |
| 79 |
|
| 80 |
>>> row = Row() |
| 81 |
>>> row.values = [struct_pb2.Value(string_value="hello")] |
| 82 |
Traceback (most recent call last): |
| 83 |
File "<stdin>", line 1, in <module> |
| 84 |
File "/usr/local/google/home/busunkim/github/python-automl/.nox/unit-3-8/lib/python3.8/site-packages/proto/message.py", line 543, in __setattr__ |
| 85 |
self._pb.MergeFrom(self._meta.pb(**{key: pb_value})) |
| 86 |
TypeError: Value must be iterable |
| 87 |
|
| 88 |
|
| 89 |
Map fields |
| 90 |
---------- |
| 91 |
|
| 92 |
Similarly, some fields are map fields. In protocol buffers, map fields are |
| 93 |
equivalent to typed dictionaries, where the keys are either strings or |
| 94 |
integers, and the values can be any type. In protocol buffers, these use |
| 95 |
a special ``map`` syntax: |
| 96 |
|
| 97 |
.. code-block:: protobuf |
| 98 |
|
| 99 |
message Album { |
| 100 |
map<uint32, Song> track_list = 1; |
| 101 |
string publisher = 2; |
| 102 |
} |
| 103 |
|
| 104 |
Declare them in Python using the :class:`~.MapField` class: |
| 105 |
|
| 106 |
.. code-block:: python |
| 107 |
|
| 108 |
class Album(proto.Message): |
| 109 |
track_list = proto.MapField(proto.UINT32, Song, number=1) |
| 110 |
publisher = proto.Field(proto.STRING, number=2) |
| 111 |
|
| 112 |
|
| 113 |
Oneofs (mutually-exclusive fields) |
| 114 |
---------------------------------- |
| 115 |
|
| 116 |
Protocol buffers allows certain fields to be declared as mutually exclusive. |
| 117 |
This is done by wrapping fields in a ``oneof`` syntax: |
| 118 |
|
| 119 |
.. code-block:: protobuf |
| 120 |
|
| 121 |
import "google/type/postal_address.proto"; |
| 122 |
|
| 123 |
message AlbumPurchase { |
| 124 |
Album album = 1; |
| 125 |
oneof delivery { |
| 126 |
google.type.PostalAddress postal_address = 2; |
| 127 |
string download_uri = 3; |
| 128 |
} |
| 129 |
} |
| 130 |
|
| 131 |
When using this syntax, protocol buffers will enforce that only one of the |
| 132 |
given fields is set on the message, and setting a field within the oneof |
| 133 |
will clear any others. |
| 134 |
|
| 135 |
Declare this in Python using the ``oneof`` keyword-argument, which takes |
| 136 |
a string (which should match for all fields within the oneof): |
| 137 |
|
| 138 |
.. code-block:: python |
| 139 |
|
| 140 |
from google.type.postal_address import PostalAddress |
| 141 |
|
| 142 |
class AlbumPurchase(proto.Message): |
| 143 |
album = proto.Field(Album, number=1) |
| 144 |
postal_address = proto.Field(PostalAddress, number=2, oneof='delivery') |
| 145 |
download_uri = proto.Field(proto.STRING, number=3, oneof='delivery') |
| 146 |
|
| 147 |
.. warning:: |
| 148 |
|
| 149 |
``oneof`` fields **must** be declared consecutively, otherwise the C |
| 150 |
implementation of protocol buffers will reject the message. They need not |
| 151 |
have consecutive field numbers, but they must be declared in consecutive |
| 152 |
order. |
| 153 |
|
| 154 |
.. warning:: |
| 155 |
|
| 156 |
If a message is constructed with multiple variants of a single ``oneof`` passed |
| 157 |
to its constructor, the **last** keyword/value pair passed will be the final |
| 158 |
value set. |
| 159 |
|
| 160 |
This is consistent with PEP-468_, which specifies the order that keyword args |
| 161 |
are seen by called functions, and with the regular protocol buffers runtime, |
| 162 |
which exhibits the same behavior. |
| 163 |
|
| 164 |
Example: |
| 165 |
|
| 166 |
.. code-block:: python |
| 167 |
|
| 168 |
import proto |
| 169 |
|
| 170 |
class Song(proto.Message): |
| 171 |
name = proto.Field(proto.STRING, number=1, oneof="identifier") |
| 172 |
database_id = proto.Field(proto.STRING, number=2, oneof="identifier") |
| 173 |
|
| 174 |
s = Song(name="Canon in D minor", database_id="b5a37aad3") |
| 175 |
assert "database_id" in s and "name" not in s |
| 176 |
|
| 177 |
s = Song(database_id="e6aa708c7e", name="Little Fugue") |
| 178 |
assert "name" in s and "database_id" not in s |
| 179 |
|
| 180 |
To query which ``oneof`` is present in a given message, use ``proto.Message._pb("oneof")``. |
| 181 |
|
| 182 |
Example: |
| 183 |
|
| 184 |
.. code-block:: python |
| 185 |
|
| 186 |
import proto |
| 187 |
|
| 188 |
class Song(proto.Message): |
| 189 |
name = proto.Field(proto.STRING, number=1, oneof="identifier") |
| 190 |
database_id = proto.Field(proto.STRING, number=2, oneof="identifier") |
| 191 |
|
| 192 |
s = Song(name="Canon in D minor") |
| 193 |
assert s._pb.WhichOneof("identifier") == "name" |
| 194 |
|
| 195 |
s = Song(database_id="e6aa708c7e") |
| 196 |
assert s._pb.WhichOneof("identifier") == "database_id" |
| 197 |
|
| 198 |
|
| 199 |
Optional fields |
| 200 |
--------------- |
| 201 |
|
| 202 |
All fields in protocol buffers are optional, but it is often necessary to |
| 203 |
check for field presence. Sometimes legitimate values for fields can be falsy, |
| 204 |
so checking for truthiness is not sufficient. Proto3 v3.12.0 added the |
| 205 |
``optional`` keyword to field descriptions, which enables a mechanism for |
| 206 |
checking field presence. |
| 207 |
|
| 208 |
In proto plus, fields can be marked as optional by passing ``optional=True`` |
| 209 |
in the constructor. The message *class* then gains a field of the same name |
| 210 |
that can be used to detect whether the field is present in message *instances*. |
| 211 |
|
| 212 |
.. code-block:: python |
| 213 |
|
| 214 |
class Song(proto.Message): |
| 215 |
composer = proto.Field(Composer, number=1) |
| 216 |
title = proto.Field(proto.STRING, number=2) |
| 217 |
lyrics = proto.Field(proto.STRING, number=3) |
| 218 |
year = proto.Field(proto.INT32, number=4) |
| 219 |
performer = proto.Field(proto.STRING, number=5, optional=True) |
| 220 |
|
| 221 |
>>> s = Song( |
| 222 |
... composer={'given_name': 'Johann', 'family_name': 'Pachelbel'}, |
| 223 |
... title='Canon in D', |
| 224 |
... year=1680, |
| 225 |
... genre=Genre.CLASSICAL, |
| 226 |
... ) |
| 227 |
>>> Song.performer in s |
| 228 |
False |
| 229 |
>>> s.performer = 'Brahms' |
| 230 |
>>> Song.performer in s |
| 231 |
True |
| 232 |
>>> del s.performer |
| 233 |
>>> Song.performer in s |
| 234 |
False |
| 235 |
>>> s.performer = "" # The mysterious, unnamed composer |
| 236 |
>>> Song.performer in s |
| 237 |
True |
| 238 |
|
| 239 |
|
| 240 |
Under the hood, fields marked as optional are implemented via a synthetic |
| 241 |
one-variant ``oneof``. See the protocolbuffers documentation_ for more |
| 242 |
information. |
| 243 |
|
| 244 |
.. _documentation: https://github.com/protocolbuffers/protobuf/blob/v3.12.0/docs/field_presence.md |
| 245 |
|
| 246 |
.. _PEP-468: https://www.python.org/dev/peps/pep-0468/ |