Protobuf: Enum values not defined in enum class

Created on 12 Apr 2019  路  4Comments  路  Source: protocolbuffers/protobuf

The documentation for enum says:

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

enum SomeEnum {
    VALUE_A = 0;
    VALUE_B = 5;
    VALUE_C = 1234;
}
value-a = myproto_pb2.SomeEnum.VALUE_A
# or
myproto_pb2.VALUE_A
# or
myproto_pb2.SomeEnum.Value('VALUE_A')

But value-a = myproto_pb2.SomeEnum.VALUE_A fails.

What version of protobuf and what language are you using?
Version: v3.7.1/v3.6.1
Language: Python

What operating system (Linux, Windows, ...) and version?
Xubuntu 18.04

What runtime / compiler are you using (e.g., python version or gcc version)
gcc

What did you do?

  1. Save the proto definition from the documentation to a file name myproto.proto.
  2. Generate the python code:
./protoc --python_out=. --proto_path=. myproto.proto 
  1. Attempt to access the value in the ways the documentation demonstrates.
python -c "import myproto_pb2; print(myproto_pb2.SomeEnum.Value('VALUE_A')); print(myproto_pb2.VALUE_A); print(myproto_pb2.SomeEnum.VALUE_A);"

What did you expect to see

0
0

What did you see instead?

0
Traceback (most recent call last):
  File "<string>", line 1, in <module>
AttributeError: 'EnumTypeWrapper' object has no attribute 'VALUE_A'
customer issue python wait for 3.8.0 release

Most helpful comment

@pkalebu It looks like you have to do myproto_pb2.SomeEnum.Value('VALUE_A')

All 4 comments

Oh, we updated the document earlier than it should be. The __getattr__ is added in this PR which is not release in v3.7.1:
https://github.com/protocolbuffers/protobuf/commit/0de6577b7d5702a133f0eade4ddf6b94893e975a#diff-abebaaaa517a7cbc213cb3d39c6e444b

what's the correct way to get the value of an enum then?

@pkalebu It looks like you have to do myproto_pb2.SomeEnum.Value('VALUE_A')

@markisus Thanks for this, looks like the documentation needs quite some updates to conform to Proto3 馃槄

Would've needed to read the actual commit changes to get the answer to read the enum values.
Unfortunately due to this changes, even the most downloaded VS-Code plugin will show errors for valid code...

Do they have their documentation source open?
I think I'd be able to update some of it since I'm writing a blog post about it anyway 馃槃

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bullyork picture bullyork  路  3Comments

TimmKayserHere picture TimmKayserHere  路  3Comments

louwersj picture louwersj  路  4Comments

nvarini picture nvarini  路  3Comments

monark12 picture monark12  路  3Comments