Python Generated Code Guide

Any differences between proto2 and proto3 generated code are highlighted - note that these differences are in the generated code as described in this document, not the base message classes/interfaces, which are the same in both versions. You should read the proto2 language guide and/or proto3 language guide before reading this document.

The Python Protocol Buffers implementation is a little different from C++ and Java. In Python, the compiler only outputs code to build descriptors for the generated classes, and a Python metaclass does the real work. This document describes what you get after the metaclass has been applied.

Compiler Invocation

The protocol buffer compiler produces Python output when invoked with the --python_out= command-line flag. The parameter to the --python_out= option is the directory where you want the compiler to write your Python output. The compiler creates a .py file for each .proto file input. The names of the output files are computed by taking the name of the .proto file and making two changes:

  • The extension ( .proto ) is replaced with _pb2.py .
  • The proto path (specified with the --proto_path= or -I command-line flag) is replaced with the output path (specified with the --python_out= flag).

So, for example, let’s say you invoke the compiler as follows:

The compiler will read the files src/foo.proto and src/bar/baz.proto and produce two output files: build/gen/foo_pb2.py and build/gen/bar/baz_pb2.py . The compiler will automatically create the directory build/gen/bar if necessary, but it will not create build or build/gen ; they must already exist.

Protoc can generate Python stubs ( .pyi ) using the --pyi_out parameter.

Note that if the .proto file or its path contains any characters which cannot be used in Python module names (for example, hyphens), they will be replaced with underscores. So, the file foo-bar.proto becomes the Python file foo_bar_pb2.py .

The Python code generated by the protocol buffer compiler is completely unaffected by the package name defined in the .proto file. Instead, Python packages are identified by directory structure.

Given a simple message declaration:

The protocol buffer compiler generates a class called Foo , which subclasses google.protobuf.Message . The class is a concrete class; no abstract methods are left unimplemented. Unlike C++ and Java, Python generated code is unaffected by the optimize_for option in the .proto file; in effect, all Python code is optimized for code size.

If the message’s name is a Python keyword, then its class will only be accessible via getattr() , as described in the Names which conflict with Python keywords section.

You should not create your own Foo subclasses. Generated classes are not designed for subclassing and may lead to "fragile base class" problems. Besides, implementation inheritance is bad design.

Python message classes have no particular public members other than those defined by the Message interface and those generated for nested fields, messages, and enum types (described below). Message provides methods you can use to check, manipulate, read, or write the entire message, including parsing from and serializing to binary strings. In addition to these methods, the Foo class defines the following static methods:

  • FromString(s) : Returns a new message instance deserialized from the given string.

Note that you can also use the text_format module to work with protocol messages in text format: for example, the Merge() method lets you merge an ASCII representation of a message into an existing message.

Nested Types

A message can be declared inside another message. For example:

In this case, the Bar class is declared as a static member of Foo , so you can refer to it as Foo.Bar .

Well Known Types

Protocol buffers provides a number of well-known types that you can use in your .proto files along with your own message types. Some WKT messages have special methods in addition to the usual protocol buffer message methods, as they subclass both google.protobuf.Message and a WKT class.

For Any messages, you can call Pack() to pack a specified message into the current Any message, or Unpack() to unpack the current Any message into a specified message. For example:

Unpack() also checks the descriptor of the passed-in message object against the stored one and returns False if they don’t match and does not attempt any unpacking; True otherwise.

You can also call the Is() method to check if the Any message represents the given protocol buffer type. For example:

Use the TypeName() method to retrieve the protobuf type name of an inner message.

Timestamp messages can be converted to/from RFC 3339 date string format (JSON string) using the ToJsonString() / FromJsonString() methods. For example:

You can also call GetCurrentTime() to fill the Timestamp message with current time:

To convert between other time units since epoch, you can call ToNanoseconds(), FromNanoseconds(), ToMicroseconds(), FromMicroseconds(), ToMilliseconds(), FromMilliseconds(), ToSeconds() , or FromSeconds() . The generated code also has ToDatetime() and FromDatetime() methods to convert between Python datetime objects and Timestamps. For example:

Duration messages have the same methods as Timestamp to convert between JSON string and other time units. To convert between timedelta and Duration, you can call ToTimedelta() or FromTimedelta . For example:

FieldMask messages can be converted to/from JSON string using the ToJsonString() / FromJsonString() methods. In addition, a FieldMask message has the following methods:

  • IsValidForDescriptor(message_descriptor) : Checks whether the FieldMask is valid for Message Descriptor.
  • AllFieldsFromDescriptor(message_descriptor) : Gets all direct fields of Message Descriptor to FieldMask.
  • CanonicalFormFromMask(mask) : Converts a FieldMask to the canonical form.
  • Union(mask1, mask2) : Merges two FieldMasks into this FieldMask.
  • Intersect(mask1, mask2) : Intersects two FieldMasks into this FieldMask.
  • MergeMessage(source, destination, replace_message_field=False, replace_repeated_field=False) : Merges fields specified in FieldMask from source to destination.

Struct messages let you get and set the items directly. For example:

To get or create a list/struct, you can call get_or_create_list() / get_or_create_struct() . For example:

A ListValue message acts like a Python sequence that lets you do the following:

To add a ListValue/Struct, call add_list() / add_struct() . For example:

For each field in a message type, the corresponding class has a property with the same name as the field. How you can manipulate the property depends on its type.

As well as a property, the compiler generates an integer constant for each field containing its field number. The constant name is the field name converted to upper-case followed by _FIELD_NUMBER . For example, given the field optional int32 foo_bar = 5; , the compiler will generate the constant FOO_BAR_FIELD_NUMBER = 5 .

If the field’s name is a Python keyword, then its property will only be accessible via getattr() and setattr() , as described in the Names which conflict with Python keywords section.

Singular Fields (proto2)

If you have a singular (optional or required) field foo of any non-message type, you can manipulate the field foo as if it were a regular field. For example, if foo ’s type is int32 , you can say:

Note that setting foo to a value of the wrong type will raise a TypeError .

If foo is read when it is not set, its value is the default value for that field. To check if foo is set, or to clear the value of foo , you must call the HasField() or ClearField() methods of the Message interface. For example:

Singular Fields (proto3)

If you have a singular field foo of any non-message type, you can manipulate the field foo as if it were a regular field. For example, if foo ’s type is int32 , you can say:

If foo is read when it is not set, its value is the default value for that field. To clear the value of foo and reset it to the default value for its type, you call the ClearField() method of the Message interface. For example:

Singular Message Fields

Message types work slightly differently. You cannot assign a value to an embedded message field. Instead, assigning a value to any field within the child message implies setting the message field in the parent. You can also use the parent message’s HasField() method to check if a message type field value has been set.

So, for example, let’s say you have the following .proto definition:

You cannot do the following:

Instead, to set bar , you simply assign a value directly to a field within bar , and - presto! - foo has a bar field:

Similarly, you can set bar using the Message interface’s CopyFrom() method. This copies all the values from another message of the same type as bar .

Note that simply reading a field inside bar does not set the field:

If you need the "has" bit on a message that does not have any fields you can or want to set, you may use the SetInParent() method.

Repeated Fields

Repeated fields are represented as an object that acts like a Python sequence. As with embedded messages, you cannot assign the field directly, but you can manipulate it. For example, given this message definition:

You can do the following:

The ClearField() method of the Message interface works in addition to using Python del .

When using the index to retrieve a value, you can use negative numbers, such as using -1 to retrieve the last element in the list. If your index goes out of bounds, you’ll get an IndexError: list index out of range .

Repeated Message Fields

Repeated message fields work similar to repeated scalar fields. However, the corresponding Python object also has an add() method that creates a new message object, appends it to the list, and returns it for the caller to fill in. Also, the object’s append() method makes a copy of the given message and appends that copy to the list. This is done so that messages are always owned by the parent message to avoid circular references and other confusion that can happen when a mutable data structure has multiple owners. Similarly, the object’s extend() method appends an entire list of messages, but makes a copy of every message in the list.

For example, given this message definition:

Unlike repeated scalar fields, repeated message fields don’t support item assignment (i.e. __setitem__ ). For example:

Groups (proto2)

Note that groups are deprecated and should not be used when creating new message types – use nested message types instead.

A group combines a nested message type and a field into a single declaration, and uses a different wire format for the message. The generated message has the same name as the group. The generated field’s name is the lowercased name of the group.

For example, except for wire format, the following two message definitions are equivalent:

A group is either required , optional , or repeated . A required or optional group is manipulated using the same API as a regular singular message field. A repeated group is manipulated using the same API as a regular repeated message field.

For example, given the above SearchResponse definition, you can do the following:

Given this message definition:

The generated Python API for the map field is just like a Python dict :

As with embedded message fields , messages cannot be directly assigned into a map value. Instead, to add a message as a map value you reference an undefined key , which constructs and returns a new submessage:

You can find out more about undefined keys in the next section.

Referencing undefined keys

The semantics of Protocol Buffer maps behave slightly differently to Python dict s when it comes to undefined keys. In a regular Python dict , referencing an undefined key raises a KeyError exception:

However, in Protocol Buffers maps, referencing an undefined key creates the key in the map with a zero/false/empty value. This behavior is more like the Python standard library defaultdict .

This behavior is especially convenient for maps with message type values, because you can directly update the fields of the returned message.

Note that even if you don’t assign any values to message fields, the submessage is still created in the map:

This is different from regular embedded message fields , where the message itself is only created once you assign a value to one of its fields.

As it may not be immediately obvious to anyone reading your code that m.message_map[10] alone, for example, may create a submessage, we also provide a get_or_create() method that does the same thing but whose name makes the possible message creation more explicit:

Enumerations

In Python, enums are just integers. A set of integral constants are defined corresponding to the enum’s defined values. For example, given:

The constants VALUE_A , VALUE_B , and VALUE_C are defined with values 0, 5, and 1234, respectively. You can access SomeEnum if desired. If an enum is defined in the outer scope, the values are module constants; if it is defined within a message (like above), they become static members of that message class.

For example, you can access the values in the three following ways for the following enum in a proto:

An enum field works just like a scalar field.

If the enum’s name (or an enum value) is a Python keyword, then its object (or the enum value’s property) will only be accessible via getattr() , as described in the Names which conflict with Python keywords section.

The values you can set in an enum depend on your protocol buffers version:

  • In proto2 , an enum cannot contain a numeric value other than those defined for the enum type. If you assign a value that is not in the enum, the generated code will throw an exception.
  • proto3 uses open enum semantics: enum fields can contain any int32 value.

Enums have a number of utility methods for getting field names from values and vice versa, lists of fields, and so on - these are defined in enum_type_wrapper.EnumTypeWrapper (the base class for generated enum classes). So, for example, if you have the following standalone enum in myproto.proto :

…you can do this:

For an enum declared within a protocol message, such as Foo above, the syntax is similar:

If multiple enum constants have the same value (aliases), the first constant defined is returned.

In the above example, myproto_pb2.SomeEnum.Name(5) returns "VALUE_B" .

Given a message with a oneof:

The Python class corresponding to Foo will have properties called name and serial_number just like regular fields . However, unlike regular fields, at most one of the fields in a oneof can be set at a time, which is ensured by the runtime. For example:

The message class also has a WhichOneof method that lets you find out which field (if any) in the oneof has been set. This method returns the name of the field that is set, or None if nothing has been set:

HasField and ClearField also accept oneof names in addition to field names:

Note that calling ClearField on a oneof just clears the currently set field.

Names which conflict with Python keywords

If the name of a message, field, enum, or enum value is a Python keyword , then the name of its corresponding class or property will be the same, but you’ll only be able to access it using Python’s getattr() and setattr() built-in functions, and not via Python’s normal attribute reference syntax (i.e. the dot operator).

For example, if you have the following .proto definition:

You would access those fields like this:

By contrast, trying to use obj.attr syntax to access these fields results in Python raising syntax errors when parsing your code:

Extensions (proto2 only)

Given a message with an extension range:

The Python class corresponding to Foo will have a member called Extensions , which is a dictionary mapping extension identifiers to their current values.

Given an extension definition:

The protocol buffer compiler generates an "extension identifier" called bar . The identifier acts as a key to the Extensions dictionary. The result of looking up a value in this dictionary is exactly the same as if you accessed a normal field of the same type. So, given the above example, you could do:

Note that you need to specify the extension identifier constant, not just a string name: this is because it’s possible for multiple extensions with the same name to be specified in different scopes.

Analogous to normal fields, Extensions[...] returns a message object for singular messages and a sequence for repeated fields.

The Message interface’s HasField() and ClearField() methods do not work with extensions; you must use HasExtension() and ClearExtension() instead. To use the HasExtension() and ClearExtension() methods, pass in the field_descriptor for the extension you are checking for the existence of.

If the .proto file contains the following line:

Then the protocol buffer compiler will generate code based on the service definitions found in the file as described in this section. However, the generated code may be undesirable as it is not tied to any particular RPC system, and thus requires more levels of indirection that code tailored to one system. If you do NOT want this code to be generated, add this line to the file:

If neither of the above lines are given, the option defaults to false , as generic services are deprecated. (Note that prior to 2.4.0, the option defaults to true )

RPC systems based on .proto -language service definitions should provide plugins to generate code appropriate for the system. These plugins are likely to require that abstract services are disabled, so that they can generate their own classes of the same names. Plugins are new in version 2.3.0 (January 2010).

The remainder of this section describes what the protocol buffer compiler generates when abstract services are enabled.

Given a service definition:

The protocol buffer compiler will generate a class Foo to represent this service. Foo will have a method for each method defined in the service definition. In this case, the method Bar is defined as:

The parameters are equivalent to the parameters of Service.CallMethod() , except that the method_descriptor argument is implied.

These generated methods are intended to be overridden by subclasses. The default implementations simply call controller.SetFailed() with an error message indicating that the method is unimplemented, then invoke the done callback. When implementing your own service, you must subclass this generated service and implement its methods as appropriate.

Foo subclasses the Service interface. The protocol buffer compiler automatically generates implementations of the methods of Service as follows:

  • GetDescriptor : Returns the service’s ServiceDescriptor .
  • CallMethod : Determines which method is being called based on the provided method descriptor and calls it directly.
  • GetRequestClass and GetResponseClass : Returns the class of the request or response of the correct type for the given method.

The protocol buffer compiler also generates a "stub" implementation of every service interface, which is used by clients wishing to send requests to servers implementing the service. For the Foo service (above), the stub implementation Foo_Stub will be defined.

Foo_Stub is a subclass of Foo . Its constructor takes an RpcChannel as a parameter. The stub then implements each of the service’s methods by calling the channel’s CallMethod() method.

The Protocol Buffer library does not include an RPC implementation. However, it includes all of the tools you need to hook up a generated service class to any arbitrary RPC implementation of your choice. You need only provide implementations of RpcChannel and RpcController .

Plugin Insertion Points

Code generator plugins which want to extend the output of the Python code generator may insert code of the following types using the given insertion point names.

  • imports : Import statements.
  • module_scope : Top-level declarations.

Sharing Messages Between Python and C++

Prior to the 4.21.0 version of the Protobuf Python API, Python apps could share messages with C++ using a native extension. Starting in the 4.21.0 API version, sharing messages between Python and C++ is not supported by the default install. To enable this capability when working with the 4.x and later versions of the Protobuf Python API, define the environment variable, PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=cpp , and ensure that the Python/C++ extension is installed.

Python使用Protobuf&&如何赋值&&如何正反序列化

python protobuf assignment not allowed to field

使用protobuf主要是两个步骤, 序列化和反序列化 。

关于Proto有哪些数据类型,然后如何编写,此处就不赘述了,百度一下有很多。

此文主要是总结,python使用protobuf的过程,如何序列化和反序列化,对不同类型的字段如何进行赋值。

在本文最后,给出了一个本文的示例接口,你可以试试请求接口,体验一下 gRPC 的传输方式。

下面将一一列举各数据类型,在python中如何正确赋值,赋值后如何序列化。

首先,得把编译包给导入

我分为两部分,分别为未被 repeated 修饰的字段 和 被 repeated 修饰后的字段

创建message对象,然后赋值即可。与python中,通过类创建实例, 实例.属性 的方式进行赋值类似

我们看到在 SearchService 里序号为 3 的字段的类型为 SearchRequest ,这是我们新定义的message

如果把message看作是一个类,那么我将其实例化,然后赋值给对应的字段,可以吗?

ok,这是不行的,错误示例:

image-20210116211914264

不允许在协议消息对象中分配复合字段“searchRequest”。

正确示例:

如果加上之前的那个字段,那么这样的:

枚举类型,注意一点: 必须包含一个含0的字段

在这里插入图片描述

序号为4,类型为 SearchType 的枚举类,名为 searchType 的字段

此处的枚举类型,你可以看作是网页中的单选框,只能从给定的数据中选择一个,不选则默认为0

被repeated修饰的字段

uid 的类型是 int32 ,然后被 repeated 修饰,即这个字段是可重复赋值的。

那么,在python中应该怎么赋值呢?

错误示例:

如果还是和之前一样的赋值,就会报错

AttributeError: Assignment not allowed to repeated field “uid” in protocol message object.

所以,你可以将被 repeated 修饰的字段看作是一个空列表,往里添加值即可!

seconds 字段是可重复的 message 类型,在python中该如何赋值?

或者,你也可以这样

或者这样:

所以, repeated 修饰的字段,在python中,就是一个列表

使用方法与之前的完全一致

现在我们已经全部赋值好了,接着就是序列化了

SerializeToString

Serializes the protocol message to a binary string. 序列化此协议消息为二进制串

现在,我们是接收方,我们收到了一串二进制。

首先,我们需要使用将其反序列化,同样使用编译包。

ParseFromString 解析函数

此时, search_service 就已经含有传输过来的全部数据了。如果你不想使用 对象.属性 的方式调用,或者想使用类似 json.loads 直接转为python中的字典,那么你可以使用 protobuf_to_dict 将其转为字典。

安装protobuf3_to_dict`

本文中例子,我做了一个接口。

接口地址: http://47.101.154.110:8000/

请求头请求体请求方式
必须指定Content-Type: application/grpc-web+proto序列化后的二进制POST

你可以使用 postman 提交数据,来查看结果

也可以使用Python发送请求

完整的 test.proto

在使用编译包时,没有代码提示,还有点不习惯。

这里,推荐安装 mypy-protobuf

使用方法:

在你使用 protoc 命令编译proto文件时,新增一个参数 mypy-out= ,就像这样

此时会生成两个文件,并将他们拖入项目中的同一目录

test_pb2.py :我们需要导入使用的编译包

test_pb2.pyi :存根文件,在编辑器中会有代码提示(想了解存根文件,可以看最下面的参考文章)

效果演示:

https://github.com/dropbox/mypy-protobuf

pyi文件是干嘛的?(一文读懂Python的存根文件和类型检查)

python protobuf assignment not allowed to field

“相关推荐”对你有帮助么?

python protobuf assignment not allowed to field

请填写红包祝福语或标题

python protobuf assignment not allowed to field

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。 2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

python protobuf assignment not allowed to field

python protobuf assignment not allowed to field

Assignment not allowed to repeated field "conversions" in protocol message object

panu.kuu...@hopkins.fi's profile photo

[email protected]

Send Downlink command as JSON via gRPC and Python with use of payload formatter

Hey, I’m trying to send a downlink command via gRPC and Python to an existing device. It works to a point, but I tried to send a JSON, which then should get processed via the payload formatter. The problem is that if I send the JSON as an utf-8 encoded string, it does not get passed through the payload format but gets enqueued directly to the device. I tried to assign the req.queue_item.object, but it gives me an error (“AttributeError: Assignment not allowed to message, map, or repeated field “object” in the protocol message object.”). Is there a way to send a downlink to chirpstack with a JSON so that the payload formatter can encode it for the device?

Are you testing this against ChirpStack v3 or v4?

Hey, We use ChirpStack v4 and the corresponding PyPI library.

@brocaar , is this a bug, or is this functionality not yet implemented?

Where in v3 you had to pass the JSON object as string, you must pass it as JSON object in v4 ( https://github.com/chirpstack/chirpstack/blob/master/api/proto/api/device.proto#L483 ).

@brocaar I know, but if I set it to either a python JSON object or a google.protobuf.Struct it returns:

And what do I do with the data field, I can’t let it be empty.

I’m not familiar with the Python API for Protobuf struct types, but maybe this could help you? dictionary - How do you create a Protobuf Struct from a Python Dict? - Stack Overflow

@brocaar I tried that before but same message:

I think there is something else wrong. Maybe the word object is conflicting with something in python? Or something went wrong with the code generation for python. But I honestly don’t know how to debug this.

Found the solution. If you use:

Instead of:

Then everything works.

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Repeated maps not allowed? #3672

@alexkreidler

alexkreidler commented Sep 21, 2017

I have this line in my proto:

I get this error:

Is this by design? I am trying to provide interoperability with JSON, and I want my JSON to look like:

I understand this would not provide a deterministic number of keys for the protobuf system, but we could implement this behind-the-scenes with an array or of and .

I might this up at , and try to figure out a way to implement this in the parser.

Is there any way to allow this use-case? I really love protobufs and I don't want to do any custom preprocessing.

Never mind, just read the docs.

  • 👎 4 reactions
  • 😕 1 reaction

Sorry, something went wrong.

@alexkreidler

No branches or pull requests

@alexkreidler

python - 属性错误 : Assignment not allowed to composite field "task" in protocol message object

标签 python protocol-buffers

我正在使用protocol-buffers python lib发送数据,但它有一些问题,所以

原型(prototype)文件:

试试 CopyFrom :

关于python - 属性错误 : Assignment not allowed to composite field "task" in protocol message object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18376190/

上一篇: Python:我可以有一个带有命名索引的列表吗?

下一篇: python - notepad++ 中 python 的自动缩进.

python - 如何递归替换嵌套字典键中的字符?

javascript - 在本地主机上使用 TLS 的 Web gRPC

java - 将 byte[] 解析回 Protocol Buffer 消息实例时出现 RuntimeException! (反序列化)

c++ - 在 Bazel 中包含 Protobufs

python - 是否有一致的方法从 ttk 小部件中删除焦点矩形

python - 在 GAE/P 中创建您自己的事件日志

python - Django 会在用户登录时刷新 request.session 对象吗?

python - 计算归并排序的反转

javascript - 你如何在 Node 中解码 gtfs protobufs

hadoop - 是否有可用于 lzo 压缩二进制数据的 Scalding 源?

©2024 IT工具网   联系我们

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

How is protobuf generating this method and is it impossible to get auto-complete for it?

I was looking at a code base (GCP SDK's monitoring API) trying to drill down to get familiar with some methods, but I hit a wall here: https://cloud.google.com/monitoring/custom-metrics/creating-metrics#monitoring_create_metric-python

Specifically this line descriptor = ga_metric.MetricDescriptor() . How does MetricDescriptor() get generated?

According to comments in metric_pb2 (ga_metric is an alias to it) that file was generated by protobuf. In that module file I see no definition for MetricDescriptor() though. How am I able to call ga_metric.MetricDescriptor() ? What part of the code here is generating the MetricDescriptor() method that I'm able to call?

  • protocol-buffers
  • protobuf-python

red888's user avatar

See these three lines:

globals() returns the dict implementing the namespace of the current module, so at the module scope the following are equivalent:

By passing the return value of globals() to the two _builder.Build... functions, the code is allowing the builder to add names to the current module. That's how the builder.Build... functions can define names like MetricDescriptor .

Getting auto-complete to work despite the shenanigans is a tall order. When working with protobufs I like to view the .proto file from which the _pb2.py file is generated (probably metric.proto would generate metric_pb2.py ), alongside Google's Python Generated Code Guide .

byvire's user avatar

  • 2 A quirk of Python code generated by the protocol buffer compiler ( protoc ) is that it produces metaclasses making it difficult to decipher the classes and their methods that result but, to @byvire answer, you can infer the Python types (classes|methods) from the MetricDescriptor protobuf source or you can use protoc --pyi_out to get python interfaces –  DazWilkin Commented Jun 27 at 22:29

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python protocol-buffers protobuf-python or ask your own question .

  • The Overflow Blog
  • Community Products Roadmap Update, July 2024
  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • The [lib] tag is being burninated
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Major church father / reformer who thought Paul is one of the 24 elders in Rev 4:4 and/or one of the 12 apostles of the Lamb in Rev 21:14
  • Why didn't Jimmy Neutron realize immediately when he read the note on the refrigerator that the note is phony, as the note says "son or daughter..."?
  • Can player build dungeons in D&D? I thought that was just a job for the DM
  • Greek myth about an athlete who kills another man with a discus
  • Could two moons orbit each other around a planet?
  • Source impedance-trace impedance - load termination impedance confusion
  • Do thermodynamic cycles occur only in human-made machines?
  • Are there any parts of the US Constitution that state that the laws apply universally to all citizens?
  • Why didn't Smith give Atlas painkillers during the surgery?
  • Why danach instead of darüber?
  • Why does redirecting stderr interfere with bash's handling of $COLUMNS and the `checkwinsize` option?
  • Error handling for singly linked list in C
  • confidence intervals for proportions containing a theoretically impossible value (zero)
  • Can the US president kill at will?
  • In the UK, how do scientists address each other?
  • Should "as a ..." and "unlike ..." clauses refer to the subject?
  • How fast does the number of "fixed" points grow compared to the size of the ball in the following group?
  • Why do I see low voltage in a repaired underground cable?
  • What effects could cause a laser beam inside a pipe to bend?
  • Spec sheet on Shimano FC-C201 seemingly does not match my bike
  • Reversing vowels in a string
  • する時 referring to one-time actions/events in progress
  • How to read chainline specs for crankset and bottom bracket compatibility?
  • Were there any stone vessels made in Paleolithic?

python protobuf assignment not allowed to field

COMMENTS

  1. python

    You cannot assign a value to an embedded message field. Instead, assigning a value to any field within the child message implies setting the message field in the parent. So I'm assuming this should work: task = yacc.task() task.id = 1000 task.msg = u"test" ptask = yacc.task_info() ptask.task.id = task.id ptask.task.msg = task.msg

  2. python

    Fields in Protobuf messages have types, just as variables in programming languages like C or Java. As your id field has the type Identifier, you can only assign Identifier messages to it, not a simple int like 12. See the Protobuf Language Guide for details. -

  3. Question: How to set oneof fields in python? #5012

    Protobuf python does not support assignment for message field, even it is a normal message field instead of oneof, "test.a =" is still not allowed. "You cannot assign a value to an embedded message field. Instead, assigning a value to any field within the child message implies setting the message field in the parent. " :

  4. Protocol Buffer Basics: Python

    This tutorial provides a basic Python programmer's introduction to working with protocol buffers. By walking through creating a simple example application, it shows you how to. Define message formats in a .proto file. Use the protocol buffer compiler. Use the Python protocol buffer API to write and read messages.

  5. dynamic generation of proto objects and the error: Assignment not

    Here I get the error: Assignment not allowed to composite field "task" in protocol message object. programatically I can import this module and assign values well enough, for example in the python shell: >> import importlib. >> oobj = importlib.import_module ("dummy.dummy.test_dummy_pb2", package=None)

  6. Python Generated Code Guide

    The protocol buffer compiler generates a class called Foo, which subclasses google.protobuf.Message.The class is a concrete class; no abstract methods are left unimplemented. Unlike C++ and Java, Python generated code is unaffected by the optimize_for option in the .proto file; in effect, all Python code is optimized for code size.. If the message's name is a Python keyword, then its class ...

  7. Python使用Protobuf&&如何赋值&&如何正反序列化

    AttributeError: Assignment not allowed to repeated field "uid" in protocol message object. 正确示例: search_service. uid. append (1) search_service. uid. append (2) 所以,你可以将被repeated修饰的字段看作是一个空列表,往里添加值即可! Message. test.proto

  8. Protobuf: Question: How to set oneof fields in python?

    Protobuf python does not support assignment for message field, even it is a normal message field instead of oneof, "test.a =" is still not allowed. "You cannot assign a value to an embedded message field. Instead, assigning a value to any field within the child message implies setting the message field in the parent.

  9. What is the correct way in proto3 to use HasField? #1402

    @haberman we're using protobuf to transition from some legacy code where an enum of values is mapped to integers including a valid enum with value of 0. In my protobuf the default value is 0 even if the field is "unset". Is there a way that I can check if this field is unset without using _fields? A related issue is the value 0 isn't even ...

  10. AttributeError: Assignment not allowed to repeated field "geo_target

    AttributeError: Assignment not allowed to repeated field "geo_target_constants" in protocol message object. Can anyone tell me how i can fix this "Assignment not Allowed to repeated field" error? Thanks!

  11. [protobuf] dynamic generation of proto objects and the error

    get the error: Assignment not allowed to composite field "task" in protocol message object. programatically I can import this module and assign values well enough, for

  12. Assignment not allowed to repeated field "conversions" in protocol

    I suppose one is not allowed to assign to repeated fields but I don't see how to proceed. I think appending with request.conversions.append(click_conversion) creates a malformed request. Anyone got a clue on how to get this to work? Thank you for your help

  13. "Map fields are not allowed in oneofs" #7542

    What version of protobuf and what language are you using? Version: libprotoc 3.6.1 (proto3 syntax explicitly set in the source) Language: Go. What operating system (Linux, Windows, ...) and version? Linux, specifically gLinux Rodete. What runtime / compiler are you using (e.g., python version or gcc version)

  14. Send Downlink command as JSON via gRPC and Python with use of payload

    Hey, I'm trying to send a downlink command via gRPC and Python to an existing device. It works to a point, but I tried to send a JSON, which then should get processed via the payload formatter. The problem is that if I send the JSON as an utf-8 encoded string, it does not get passed through the payload format but gets enqueued directly to the device. I tried to assign the req.queue_item ...

  15. How to add a repeated field via reflection, in Python?

    Post by JeffD #!/usr/bin/env python import foobar_pb2 # protoc -I=. --python_out=. foobar.proto # message Bar {# optional int32 i = 1 [default = 0];

  16. Repeated maps not allowed? · Issue #3672 · protocolbuffers/protobuf

    Milestone. No milestone. Development. No branches or pull requests. 1 participant. I have this line in my proto: repeated map<string, string> dependencies = 4; I get this error: Field labels (required/optional/repeated) are not allowed on map fields.

  17. protocol buffers

    Traceback (most recent call last): File "x.py", line 8, in <module> x.data['a'] = y ValueError: Direct assignment of submessage not allowed How can I work around this problem? python

  18. python

    Traceback (most recent call last): File "test_message.py", line 17, in <module> ptask.task = task File "build\bdist.win32\egg\google\protobuf\internal\python_message.py", line 513, in setter AttributeError: Assignment not allowed to composite field "_task" in protocol message object. src如下: 原型(prototype)文件:

  19. python

    When working with protobufs I like to view the .proto file from which the _pb2.py file is generated (probably metric.proto would generate metric_pb2.py), alongside Google's Python Generated Code Guide.