Debian Codegraph @

docs/messages.rst

raw
1 Messages
2 ========
3
4 The fundamental building block in protocol buffers are `messages`_.
5 Messages are essentially permissive, strongly-typed structs (dictionaries),
6 which have zero or more fields that may themselves contain primitives or
7 other messages.
8
9 .. code-block:: protobuf
10
11 syntax = "proto3";
12
13 message Song {
14 Composer composer = 1;
15 string title = 2;
16 string lyrics = 3;
17 int32 year = 4;
18 }
19
20 message Composer {
21 string given_name = 1;
22 string family_name = 2;
23 }
24
25 The most common use case for protocol buffers is to write a ``.proto`` file,
26 and then use the protocol buffer compiler to generate code for it.
27
28
29 Declaring messages
30 ------------------
31
32 However, it is possible to declare messages directly.
33 This is the equivalent message declaration in Python, using this library:
34
35 .. code-block:: python
36
37 import proto
38
39 class Composer(proto.Message):
40 given_name = proto.Field(proto.STRING, number=1)
41 family_name = proto.Field(proto.STRING, number=2)
42
43 class Song(proto.Message):
44 composer = proto.Field(Composer, number=1)
45 title = proto.Field(proto.STRING, number=2)
46 lyrics = proto.Field(proto.STRING, number=3)
47 year = proto.Field(proto.INT32, number=4)
48
49 A few things to note:
50
51 * This library only handles proto3.
52 * The ``number`` is really a field ID. It is *not* a value of any kind.
53 * All fields are optional (as is always the case in proto3).
54 The only general way to determine whether a field was explicitly set to its
55 falsy value or not set all is to mark it ``optional``.
56 * Because all fields are optional, it is the responsibility of application logic
57 to determine whether a necessary field has been set.
58 * You can optionally define a `__protobuf__` attribute in your module which will be used
59 to differentiate messages which have the same name but exist in different modules.
60
61 .. code-block:: python
62
63 # file a.py
64 import proto
65
66 __protobuf__ = proto.module(package="a")
67
68 class A(proto.Message):
69 name = proto.Field(proto.STRING, number=1)
70
71 # file b.py
72 import proto
73
74 __protobuf__ = proto.module(package="b")
75
76 class A(proto.Message):
77 name = proto.Field(proto.STRING, number=1)
78
79 # file main.py
80 import a
81 import b
82
83 _a = a.A(name="Hello, A!")
84 _b = b.A(name="Hello, B!")
85
86 .. _messages: https://developers.google.com/protocol-buffers/docs/proto3#simple
87
88 Messages are fundamentally made up of :doc:`fields`. Most messages are nothing
89 more than a name and their set of fields.
90
91
92 Usage
93 -----
94
95 Instantiate messages using either keyword arguments or a :class:`dict`
96 (and mix and matching is acceptable):
97
98 .. code-block:: python
99
100 >>> song = Song(
101 ... composer={'given_name': 'Johann', 'family_name': 'Pachelbel'},
102 ... title='Canon in D',
103 ... year=1680,
104 ... )
105 >>> song.composer.family_name
106 'Pachelbel'
107 >>> song.title
108 'Canon in D'
109
110
111 Assigning to Fields
112 -------------------
113
114 One of the goals of proto-plus is to make protobufs feel as much like regular python
115 objects as possible. It is possible to update a message's field by assigning to it,
116 just as if it were a regular python object.
117
118 .. code-block:: python
119
120 song = Song()
121 song.composer = Composer(given_name="Johann", family_name="Bach")
122
123 # Can also assign from a dictionary as a convenience.
124 song.composer = {"given_name": "Claude", "family_name": "Debussy"}
125
126 # Repeated fields can also be assigned
127 class Album(proto.Message):
128 songs = proto.RepeatedField(Song, number=1)
129
130 a = Album()
131 songs = [Song(title="Canon in D"), Song(title="Little Fugue")]
132 a.songs = songs
133
134 .. note::
135
136 Assigning to a proto-plus message field works by making copies, not by updating references.
137 This is necessary because of memory layout requirements of protocol buffers.
138 These memory constraints are maintained by the protocol buffers runtime.
139 This behavior can be surprising under certain circumstances, e.g. trying to save
140 an alias to a nested field.
141
142 :class:`proto.Message` defines a helper message, :meth:`~.Message.copy_from` to
143 help make the distinction clear when reading code.
144 The semantics of :meth:`~.Message.copy_from` are identical to the field assignment behavior described above.
145
146 .. code-block:: python
147
148 composer = Composer(given_name="Johann", family_name="Bach")
149 song = Song(title="Tocatta and Fugue in D Minor", composer=composer)
150 composer.given_name = "Wilhelm"
151
152 # 'composer' is NOT a reference to song.composer
153 assert song.composer.given_name == "Johann"
154
155 # We CAN update the song's composer by assignment.
156 song.composer = composer
157 composer.given_name = "Carl"
158
159 # 'composer' is STILL not a reference to song.composer.
160 assert song.composer.given_name == "Wilhelm"
161
162 # It does work in reverse, though,
163 # if we want a reference we can access then update.
164 composer = song.composer
165 composer.given_name = "Gottfried"
166
167 assert song.composer.given_name == "Gottfried"
168
169 # We can use 'copy_from' if we're concerned that the code
170 # implies that assignment involves references.
171 composer = Composer(given_name="Elisabeth", family_name="Bach")
172 # We could also do Message.copy_from(song.composer, composer) instead.
173 Composer.copy_from(song.composer, composer)
174
175 assert song.composer.given_name == "Elisabeth"
176
177
178 Enums
179 -----
180
181 Enums are also supported:
182
183 .. code-block:: python
184
185 import proto
186
187 class Genre(proto.Enum):
188 GENRE_UNSPECIFIED = 0
189 CLASSICAL = 1
190 JAZZ = 2
191 ROCK = 3
192
193 class Composer(proto.Message):
194 given_name = proto.Field(proto.STRING, number=1)
195 family_name = proto.Field(proto.STRING, number=2)
196
197 class Song(proto.Message):
198 composer = proto.Field(Composer, number=1)
199 title = proto.Field(proto.STRING, number=2)
200 lyrics = proto.Field(proto.STRING, number=3)
201 year = proto.Field(proto.INT32, number=4)
202 genre = proto.Field(Genre, number=5)
203
204 All enums **must** begin with a ``0`` value, which is always the default in
205 proto3 (and, as above, indistuiguishable from unset).
206
207 Enums utilize Python :class:`enum.IntEnum` under the hood:
208
209 .. code-block:: python
210
211 >>> song = Song(
212 ... composer={'given_name': 'Johann', 'family_name': 'Pachelbel'},
213 ... title='Canon in D',
214 ... year=1680,
215 ... genre=Genre.CLASSICAL,
216 ... )
217 >>> song.genre
218 <Genre.CLASSICAL: 1>
219 >>> song.genre.name
220 'CLASSICAL'
221 >>> song.genre.value
222 1
223
224 Additionally, it is possible to provide strings or plain integers:
225
226 .. code-block:: python
227
228 >>> song.genre = 2
229 >>> song.genre
230 <Genre.JAZZ: 2>
231 >>> song.genre = 'CLASSICAL'
232 <Genre.CLASSICAL: 1>
233
234 Serialization
235 -------------
236
237 Serialization and deserialization is available through the
238 :meth:`~.Message.serialize` and :meth:`~.Message.deserialize` class methods.
239
240 The :meth:`~.Message.serialize` method is available on the message *classes*
241 only, and accepts an instance:
242
243 .. code-block:: python
244
245 serialized_song = Song.serialize(song)
246
247 The :meth:`~.Message.deserialize` method accepts a :class:`bytes`, and
248 returns an instance of the message:
249
250 .. code-block:: python
251
252 song = Song.deserialize(serialized_song)
253
254 JSON serialization and deserialization are also available from message *classes*
255 via the :meth:`~.Message.to_json` and :meth:`~.Message.from_json` methods.
256
257 .. code-block:: python
258
259 json = Song.to_json(song)
260
261 new_song = Song.from_json(json)
262
263 Similarly, messages can be converted into dictionaries via the
264 :meth:`~.Message.to_dict` helper method.
265 There is no :meth:`~.Message.from_dict` method because the Message constructor
266 already allows construction from mapping types.
267
268 .. code-block:: python
269
270 song_dict = Song.to_dict(song)
271
272 new_song = Song(song_dict)
273
274 .. note::
275
276 Although Python's pickling protocol has known issues when used with
277 untrusted collaborators, some frameworks do use it for communication
278 between trusted hosts. To support such frameworks, protobuf messages
279 **can** be pickled and unpickled, although the preferred mechanism for
280 serializing proto messages is :meth:`~.Message.serialize`.
281
282 Multiprocessing example:
283
284 .. code-block:: python
285
286 import proto
287 from multiprocessing import Pool
288
289 class Composer(proto.Message):
290 name = proto.Field(proto.STRING, number=1)
291 genre = proto.Field(proto.STRING, number=2)
292
293 composers = [Composer(name=n) for n in ["Bach", "Mozart", "Brahms", "Strauss"]]
294
295 with multiprocessing.Pool(2) as p:
296 def add_genre(comp_bytes):
297 composer = Composer.deserialize(comp_bytes)
298 composer.genre = "classical"
299 return Composer.serialize(composer)
300
301 updated_composers = [
302 Composer.deserialize(comp_bytes)
303 for comp_bytes in p.map(add_genre, (Composer.serialize(comp) for comp in composers))
304 ]