Python: Accessing a non-existent field from google.protobuf.struct_pb2.Struct creates that field

15 views
Skip to first unread message

Manuel Desbonnet

unread,
Apr 22, 2020, 11:47:46 AM4/22/20
to Protocol Buffers
With python (versions 3.6.9, 3.8.2, at least) if I create a pb2 Struct and try to access a non-existent field from that struct, a ValueError is raised, but that field is created as a side-effect.
Furthermore the field is created without a type such that it cannot be marshalled.

E.g. (using protobuf-3.11.3):
#!/usr/bin/env python

import google.protobuf.struct_pb2

s
= google.protobuf.struct_pb2.Struct()
s
['valid_str_key'] = 'blah'
s
['valid_null_key'] = None

print(f"Struct(before): >>>{s}<<<")
try:
    v
= s['bogus_key']
except ValueError:
   
pass
print(f"Struct(after): >>>{s}<<<")
assert 'bogus_key' not in s, "Struct should not contain 'bogus_key'"

When I run this, I get the following output:
Struct(before): >>>fields {
  key
: "valid_null_key"
  value
{
    null_value
: NULL_VALUE
 
}
}
fields
{
  key
: "valid_str_key"
  value
{
    string_value
: "blah"
 
}
}
<<<
Struct(after): >>>fields {
  key
: "bogus_key"
  value
{
 
}
}
fields
{
  key
: "valid_null_key"
  value
{
    null_value
: NULL_VALUE
 
}
}
fields
{
  key
: "valid_str_key"
  value
{
    string_value
: "blah"
 
}
}
<<<
Traceback (most recent call last):
 
File "pb2_struct_min_reproducer.py", line 15, in <module>
   
assert 'bogus_key' not in s, "Struct should not contain 'bogus_key'"
AssertionError: Struct should not contain 'bogus_key'



- the 'bogus_key' field now exists, which I wouldn't have expected.
- it appears to have no type (compared with str_value/null_value for the other two fields).  This causes marshalling problems for at least golang if it receives that struct over the wire and tries to marshall it.

Is this expected behaviour somehow?

Thanks,
Manuel.
Reply all
Reply to author
Forward
0 new messages