0
# Enumerations
1
2
Protobuf enumeration support with integer-based enums that provide string name conversion and integration with the message system.
3
4
## Capabilities
5
6
### Enum Base Class
7
8
The `Enum` class serves as the base for all generated protobuf enumerations, extending both `int` and `enum.Enum` for compatibility.
9
10
```python { .api }
11
class Enum(int, enum.Enum):
12
"""Protocol buffers enumeration base class. Acts like `enum.IntEnum`."""
13
14
@classmethod
15
def from_string(cls, name: str) -> int:
16
"""
17
Return the value which corresponds to the string name.
18
19
Args:
20
name: The string name of the enum value
21
22
Returns:
23
The integer value corresponding to the name
24
25
Raises:
26
ValueError: If the name is not found in the enum
27
"""
28
```
29
30
### Enum Field Creation
31
32
Function to create enum fields in message definitions.
33
34
```python { .api }
35
def enum_field(number: int, group: Optional[str] = None) -> Any:
36
"""
37
Create an enumeration field with the given protobuf field number.
38
39
Args:
40
number: Protobuf field number (must be unique within the message)
41
group: Optional one-of group name if this field is part of a one-of
42
43
Returns:
44
A dataclass field configured for enum values
45
"""
46
```
47
48
## Usage Examples
49
50
### Defining Enums
51
52
```python
53
import betterproto
54
from dataclasses import dataclass
55
56
class Status(betterproto.Enum):
57
UNKNOWN = 0
58
PENDING = 1
59
APPROVED = 2
60
REJECTED = 3
61
62
@dataclass
63
class Request(betterproto.Message):
64
id: str = betterproto.string_field(1)
65
status: Status = betterproto.enum_field(2)
66
priority: Priority = betterproto.enum_field(3, group="urgency")
67
```
68
69
### Using Enums
70
71
```python
72
# Create a request with enum values
73
request = Request(
74
id="req-123",
75
status=Status.PENDING
76
)
77
78
# Access enum values
79
print(request.status) # Status.PENDING (displays as 1)
80
print(request.status.name) # "PENDING"
81
print(request.status.value) # 1
82
83
# Convert from string names
84
status = Status.from_string("APPROVED")
85
print(status) # Status.APPROVED
86
87
# Handle unknown string names
88
try:
89
bad_status = Status.from_string("INVALID")
90
except ValueError as e:
91
print(f"Error: {e}") # Error: Unknown value INVALID for enum Status
92
```
93
94
### Enum Serialization
95
96
```python
97
# Enums serialize as their integer values
98
request = Request(id="req-123", status=Status.APPROVED)
99
100
# JSON serialization uses enum names
101
json_data = request.to_json()
102
print(json_data) # {"id": "req-123", "status": "APPROVED"}
103
104
# Dictionary conversion also uses names by default
105
dict_data = request.to_dict()
106
print(dict_data) # {"id": "req-123", "status": "APPROVED"}
107
108
# Parse from JSON with enum names
109
request_from_json = Request().from_json('{"id": "req-456", "status": "REJECTED"}')
110
print(request_from_json.status) # Status.REJECTED
111
```
112
113
### Repeated Enum Fields
114
115
```python
116
@dataclass
117
class MultiStatus(betterproto.Message):
118
statuses: List[Status] = betterproto.enum_field(1)
119
120
# Create with multiple enum values
121
multi = MultiStatus(statuses=[Status.PENDING, Status.APPROVED, Status.REJECTED])
122
123
# JSON serialization
124
json_data = multi.to_json()
125
print(json_data) # {"statuses": ["PENDING", "APPROVED", "REJECTED"]}
126
```
127
128
### Enum One-of Fields
129
130
```python
131
class Priority(betterproto.Enum):
132
LOW = 0
133
MEDIUM = 1
134
HIGH = 2
135
136
class Urgency(betterproto.Enum):
137
NORMAL = 0
138
URGENT = 1
139
CRITICAL = 2
140
141
@dataclass
142
class Task(betterproto.Message):
143
name: str = betterproto.string_field(1)
144
145
# One-of group for priority specification
146
priority: Priority = betterproto.enum_field(2, group="priority_level")
147
urgency: Urgency = betterproto.enum_field(3, group="priority_level")
148
149
# Use one-of enums
150
task = Task(name="Important Task", priority=Priority.HIGH)
151
152
# Check which one-of field is set
153
field_name, field_value = betterproto.which_one_of(task, "priority_level")
154
print(f"Priority field: {field_name} = {field_value}") # priority = Priority.HIGH
155
```
156
157
### Integration with Message Parsing
158
159
```python
160
# Enums work seamlessly with binary serialization
161
task = Task(name="Test", priority=Priority.MEDIUM)
162
163
# Serialize to binary
164
binary_data = bytes(task)
165
166
# Parse from binary - enum values are automatically converted
167
parsed_task = Task().parse(binary_data)
168
print(type(parsed_task.priority)) # <enum 'Priority'>
169
print(parsed_task.priority) # Priority.MEDIUM
170
```
171
172
## Types
173
174
```python { .api }
175
# Enum type constant
176
TYPE_ENUM: str = "enum"
177
```