@@ -299,13 +299,22 @@ def transcode(http_options, message=None, **request_kwargs):
299299 body = http_option .get ("body" )
300300
301301 # gapic-generator-python appends an underscore to field names
302- # that collide with python keywords.
303- # `_` is stripped away as it is not possible to
304- # natively define a field with a trailing underscore in protobuf.
305- # See related issue
302+ # that collide with python keywords. See related issue
306303 # https://github.com/googleapis/python-api-core/issues/227
304+ # `leftovers` can either be a dict or protobuf message.
305+ # When `leftovers` is a dict, the `_` suffix in each key
306+ # is stripped away as it is not possible to natively define a field
307+ # with a trailing underscore in protobuf.
308+ # When `leftovers` is a protobuf message, we need to use an underscore
309+ # suffix when accessing the field in the protobuf message when the
310+ # field has an underscore suffix.
311+ field_suffix = ""
312+
307313 if isinstance (leftovers , dict ):
308314 leftovers = {key .rstrip ("_" ): val for key , val in leftovers .items ()}
315+ elif body :
316+ if hasattr (leftovers , body + "_" ):
317+ field_suffix = "_"
309318
310319 if body :
311320 if body == "*" :
@@ -317,13 +326,6 @@ def transcode(http_options, message=None, **request_kwargs):
317326 else :
318327 try :
319328 if message :
320- # See above comment where gapic-generator-python appends
321- # underscores to field names that are python reserved words.
322- # If the message has an attribute with an underscore suffix,
323- # use that instead.
324- field_suffix = ""
325- if hasattr (leftovers , body + "_" ):
326- field_suffix = "_"
327329 request ["body" ] = getattr (leftovers , f"{ body } { field_suffix } " )
328330 delete_field (leftovers , f"{ body } { field_suffix } " )
329331 else :
0 commit comments