Python raises “TypeError: descriptors cannot not be created directly” when without your involvement, the latest version 4.x of the protobuf package is installed on your system.
How to Fix TypeError: descriptors cannot not be created directly
To fix the TypeError: descriptors cannot not be created directly error, you have two solutions.
- You can downgrade the protobuf package using this command: pip install protobuf==3.20.*.
- You can set the environment variable like this:
export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python
Alternate solution based on specific scenario
If there is a problem with the .proto file, you can define your messages in a .proto file and use the Protocol Buffers compiler to generate the descriptor objects.
See the sample code of the .proto file.
syntax = "proto3";
message MyMessage {
int32 id = 1;
string name = 2;
}
The next step is to use the Protocol Buffers compiler to generate the descriptors for the messages defined in the .proto file.
protoc --python_out=./ my_messages.proto
After generating the descriptors, you can use them in your code to encode and decode messages.
When you want to make a descriptor without defining it as a class attribute, you call its function directly.
A property, method, or data descriptor is an example of a descriptor that tells how an attribute of a class should behave when accessed. You can only make a descriptor by defining it as an attribute of a class.
A “descriptor” in Protocol Buffers refers to the metadata that describes the structure of a message, including its fields, types, and default values.
Sometimes the error might occur when you try to create a descriptor object directly rather than by defining a message in a .proto file and generating the descriptors using the Protocol Buffers compiler.
Conclusion
Downgrade the protobuf package to its “3.20.*” version to fix the TypeError: descriptors cannot not be created directly issue. An alternate solution is to set the environment variable.
I hope this article will fix all the issues related to this error.