【问题标题】:How to programmatically find if the object type is of Google Protobuf?如何以编程方式查找对象类型是否为 Google Protobuf?
【发布时间】:2021-10-12 23:07:32
【问题描述】:

我有一个案例,我从另一个模块接收对象。对象类型可以是 JSON String、dict 或 Google Protobuf。我可以在 python 中使用 isinstance 来确定它是 JSON String 还是 dict,但是发现很难使用 isinstance 来检查它是否是 protobuf。我什至不确定isinstance 是否可以用于 Google Protobuf 等非原始类型。

那么,有没有办法在 Python 中检查给定对象是否属于 Google Protobuf 类型?

【问题讨论】:

  • 如果类型只能是三个中的一个,为什么不检查前两个并假设它是关联else 中的 Protobuf?
  • 一种方法(不确定在这种情况下是否最好)是尝试反序列化该值并用try ... except 包装它,以在它不是有效的 Protobuf 时捕获错误。
  • I am not even sure if isinstance can be used for non primitive types like Google Protobuf. ...你能想办法找出来吗?
  • isinstance() 将适用于非原始类型。
  • user2896235:isinstance() 的文档说 classinfo 参数可以是类型对象的元组,这意味着您可以在一次调用中检查多种类型.至于@Danielle 的评论,您可以在protobuf 上尝试一下,看看它是否有效。

标签: python protocol-buffers isinstance


【解决方案1】:

您接收的是 Protobuf 对象还是序列化(二进制)字符串?

如果您正在接收对象,那么这些应该Messageisinstance 的子类,使用 object for Message 对于 protobufs 应该是 true。

如果你的传入对象是o 并且:

assert isinstance(json.loads(o), dict)
assert isinstance(o, dict)

from google.protobuf.message import Message
assert isinstance(o, Message)
assert issubclass(o, Message)

尽管对每种类型(JSON、dict、proto)进行测试需要付出更多努力,但我认为在继续之前确认对象的类型会更好。

您可以通过仅测试直到找到匹配项来缩短测试,但您希望避免将来添加某些第 4 类型,并且您的代码假设任何不是 JSON 或 dict 的东西都是原型。

【讨论】:

  • 将 Message、message、protobuf、proto 作为类型传递给 isinstance 不起作用。由于未定义名称“x”,所有案例都得到了响应。 x 是 Message、message 或 protobuf 等。
  • 如果你的传入对象是o 和你的json.loads(o)isinstance(o, dict) 那么你应该能够from google.protobuf.message import Messageisinstance(o, Message)issubclass(o, Message)
  • 优秀。这行得通。也许您应该使用此信息更新您的答案。
  • @DazWilkin 我们如何将 isinstance 与 protobuf 二进制消息一起使用?
  • 然后先反序列化它(ParseFromString)。请不要在 cmets 中提出新问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-22
  • 2010-11-16
  • 1970-01-01
  • 2018-08-10
  • 1970-01-01
  • 2017-10-28
相关资源
最近更新 更多