@@ -120,3 +120,51 @@ a string (which should match for all fields within the oneof):
120120 implementation of protocol buffers will reject the message. They need not
121121 have consecutive field numbers, but they must be declared in consecutive
122122 order.
123+
124+
125+ Optional fields
126+ ---------------
127+
128+ All fields in protocol buffers are optional, but it is often necessary to
129+ check for field presence. Sometimes legitimate values for fields can be falsy,
130+ so checking for truthiness is not sufficient. Proto3 v3.12.0 added the
131+ ``optional `` keyword to field descriptions, which enables a mechanism for
132+ checking field presence.
133+
134+ In proto plus, fields can be marked as optional by passing ``optional=True ``
135+ in the constructor. The message *class * then gains a field of the same name
136+ that can be used to detect whether the field is present in message *instances *.
137+
138+ .. code-block :: python
139+
140+ class Song (proto .Message ):
141+ composer = proto.Field(Composer, number = 1 )
142+ title = proto.Field(proto.STRING , number = 2 )
143+ lyrics = proto.Field(proto.STRING , number = 3 )
144+ year = proto.Field(proto.INT32 , number = 4 )
145+ performer = proto.Field(proto.STRING , number = 5 , optional = True )
146+
147+ >> > s = Song(
148+ ... composer = {' given_name' : ' Johann' , ' family_name' : ' Pachelbel' },
149+ ... title = ' Canon in D' ,
150+ ... year = 1680 ,
151+ ... genre = Genre.CLASSICAL ,
152+ ... )
153+ >> > Song.performer in s
154+ False
155+ >> > s.performer = ' Brahms'
156+ >> > Song.performer in s
157+ True
158+ >> > del s.performer
159+ >> > Song.performer in s
160+ False
161+ >> > s.performer = " " # The mysterious, unnamed composer
162+ >> > Song.performer in s
163+ True
164+
165+
166+ Under the hood, fields marked as optional are implemented via a synthetic
167+ one-variant ``oneof ``. See the protocolbuffers documentation _ for more
168+ information.
169+
170+ .. _documentation : https://github.com/protocolbuffers/protobuf/blob/v3.12.0/docs/field_presence.md
0 commit comments