gpt4 book ai didi

python - 如果子消息没有字段,如何在 protobuf 消息上分配一个字段?

转载 作者:行者123 更新时间:2023-12-05 04:05:46 26 4
gpt4 key购买 nike

我想创建一个 BigTable DeleteFromRow 突变。 MutationDeleteFromRow 的原型(prototype)如下所示:

oneof mutation {
// Set a cell's value.
SetCell set_cell = 1;

// Deletes cells from a column.
DeleteFromColumn delete_from_column = 2;

// Deletes cells from a column family.
DeleteFromFamily delete_from_family = 3;

// Deletes cells from the entire row.
DeleteFromRow delete_from_row = 4;
}
}

message DeleteFromRow {

}

在 Python 中,您不能直接实例化 DeleteFromRow 对象并将 Mutationdelete_from_row 字段设置为该对象。

所以这不起作用:

request = bigtable_pb2.MutateRowRequest(table_name='tablename', row_key=row_key)
mutation = request.mutations.add()
mutation.delete_from_row = data_pb2.Mutation.DeleteFromRow()

正如其他 SO 用户所提出的(参见 this question ),这导致了

AttributeError: Assignment not allowed to composite field "delete_from_row" in protocol message object.

根据protobuf docs ,您应该通过设置其中一个子字段来设置一个字段。因此,应该以这种方式创建 DeleteFromFamily 突变:

mutation.delete_from_family.family_name = 'some_family'

但是,如何为没有字段的 DeleteFromRow 消息执行此操作?

最佳答案

您可以使用 Message.SetInParent :

Mark this as present in the parent.

This normally happens automatically when you assign a field of a sub-message, but sometimes you want to make the sub-message present while keeping it empty. If you find yourself using this, you may want to reconsider your design.

例子:

message Msg {
oneof kind {
int64 int_field = 1;
EmptyMsg msg_field = 1;
}
}

message EmptyMsg {}
msg = Msg()
print(msg.WhichOneof('kind')) # None

msg.msg_field # No-op (return EmptyMsg but don't set oneof field)
print(msg.WhichOneof('kind')) # None

msg.msg_field.SetInParent()
print(v.WhichOneof('kind')) # msg_field

关于python - 如果子消息没有字段,如何在 protobuf 消息上分配一个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50793309/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com