一般来说,我有一个使用 Python 关键字“from”的 protobuf 定义。它适用于 Java/C#/C++,但当涉及到 Python 时,我无法为其赋值。
这是我的问题的详细信息。
我有一个如下的 protobuf 定义:
message Foo
{
required int64 from = 10
...
}
由于“from”字段是Python中的关键字,所以我生成python代码后,无法编译如下代码:
foo = Foo()
foo.from = 1234
然后,我尝试使用 setattr() 来设置属性:
setattr(foo, 'from', 1234)
这给了我一个 Protobuf 异常:
AttributeError: Assignment not allowed to composite field "from" in protocol message object.
我目前无法更改定义,因为它已在系统中广泛使用。如果我能解决在 Python 中使用“from”属性的问题,我们将不胜感激。
下面是 ProtoBuf 生成的代码:
import sys
_FOO = _descriptor.Descriptor(
name='Foo',
full_name='com.kerneljoy.Foo',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
_descriptor.FieldDescriptor(
name='from', full_name='com.kerneljoy.Foo.from', index=0,
number=10, type=3, cpp_type=2, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
extension_ranges=[],
oneofs=[
],
serialized_start=28,
serialized_end=47,
)
DESCRIPTOR.message_types_by_name['Foo'] = _FOO
Foo = _reflection.GeneratedProtocolMessageType('Foo', (_message.Message,), dict(
DESCRIPTOR = _FOO,
__module__ = 'Foo_pb2'
# @@protoc_insertion_point(class_scope:com.kerneljoy.Foo)
))
_sym_db.RegisterMessage(Foo)
最佳答案
经过几次尝试,我发现 setattr() 和 getattr() 可以解决这个问题。因为在我的生产代码中,“from”指的是另一个 protobuff 定义。所以这里的解决方案如下:
foo = Foo()
object = getattr(foo, 'from')
object.bar = 'value'
object.bar2 = 'value2'
关于python - 保留关键字在 Python 的 protobuf 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30142750/