0
# Advanced Enum Features
1
2
Specialized enumeration classes that provide automatic numbering, ordering, uniqueness constraints, and multi-value support for complex enumeration needs.
3
4
## Capabilities
5
6
### AutoNumberEnum
7
8
Enumeration that automatically assigns increasing integer values starting from 1. Useful when you need sequential numbering but don't want to manually specify values.
9
10
```python { .api }
11
class AutoNumberEnum(Enum):
12
def _generate_next_value_(name, start, count, last_values):
13
"""
14
Generate the next value for auto-numbered enum members.
15
16
Args:
17
name (str): Name of the enum member being created
18
start (int): Starting value (typically 1)
19
count (int): Number of existing members
20
last_values (list): List of values from existing members
21
22
Returns:
23
int: Next sequential value
24
"""
25
```
26
27
#### Usage Example
28
29
```python
30
from aenum import AutoNumberEnum
31
32
class Priority(AutoNumberEnum):
33
LOW # Gets value 1
34
MEDIUM # Gets value 2
35
HIGH # Gets value 3
36
CRITICAL # Gets value 4
37
38
print(Priority.LOW.value) # 1
39
print(Priority.CRITICAL.value) # 4
40
41
# Can mix with explicit values
42
class Status(AutoNumberEnum):
43
PENDING # Gets value 1
44
ACTIVE = 10
45
INACTIVE # Gets value 11
46
ARCHIVED # Gets value 12
47
```
48
49
### AutoEnum
50
51
Enumeration that automatically uses `_generate_next_value_` when values are missing (Python 3 only). Similar to AutoNumberEnum but with enhanced auto-value generation.
52
53
```python { .api }
54
class AutoEnum(Enum):
55
"""
56
Auto-enum that uses _generate_next_value_ for missing values (Python 3 only).
57
"""
58
```
59
60
#### Usage Example
61
62
```python
63
from aenum import AutoEnum
64
65
class Color(AutoEnum):
66
def _generate_next_value_(name, start, count, last_values):
67
return name.lower()
68
69
RED # Gets value 'red'
70
GREEN # Gets value 'green'
71
BLUE # Gets value 'blue'
72
73
print(Color.RED.value) # 'red'
74
```
75
76
### OrderedEnum
77
78
Enumeration that adds comparison operators (<, <=, >=, >) based on member values, enabling sorting and ordering of enum members.
79
80
```python { .api }
81
class OrderedEnum(Enum):
82
def __lt__(self, other):
83
"""Less than comparison based on value."""
84
85
def __le__(self, other):
86
"""Less than or equal comparison based on value."""
87
88
def __gt__(self, other):
89
"""Greater than comparison based on value."""
90
91
def __ge__(self, other):
92
"""Greater than or equal comparison based on value."""
93
```
94
95
#### Usage Example
96
97
```python
98
from aenum import OrderedEnum
99
100
class Size(OrderedEnum):
101
SMALL = 1
102
MEDIUM = 2
103
LARGE = 3
104
EXTRA_LARGE = 4
105
106
# Comparison operations
107
print(Size.SMALL < Size.LARGE) # True
108
print(Size.MEDIUM >= Size.SMALL) # True
109
print(max(Size.SMALL, Size.LARGE)) # Size.LARGE
110
111
# Sorting
112
sizes = [Size.LARGE, Size.SMALL, Size.MEDIUM]
113
sorted_sizes = sorted(sizes)
114
print(sorted_sizes) # [Size.SMALL, Size.MEDIUM, Size.LARGE]
115
```
116
117
### UniqueEnum
118
119
Enumeration that ensures all members have unique values, preventing accidental aliasing of enum members.
120
121
```python { .api }
122
class UniqueEnum(Enum):
123
"""Enum that raises ValueError if duplicate values are found."""
124
```
125
126
#### Usage Example
127
128
```python
129
from aenum import UniqueEnum
130
131
class Color(UniqueEnum):
132
RED = 1
133
GREEN = 2
134
BLUE = 3
135
# CRIMSON = 1 # Would raise ValueError: duplicate value found for 'CRIMSON': 1
136
137
# Alternative using @unique decorator
138
from aenum import Enum, unique
139
140
@unique
141
class Status(Enum):
142
ACTIVE = 1
143
INACTIVE = 2
144
PENDING = 3
145
# WAITING = 3 # Would raise ValueError
146
```
147
148
### MultiValueEnum
149
150
Enumeration where each member can have multiple values, useful when one concept can be represented by several different values.
151
152
```python { .api }
153
class MultiValueEnum(Enum):
154
"""Enum allowing members to have multiple values."""
155
156
def __new__(cls, *values):
157
"""
158
Create enum member with multiple values.
159
160
Args:
161
*values: Multiple values for this enum member
162
"""
163
```
164
165
#### Usage Example
166
167
```python
168
from aenum import MultiValueEnum
169
170
class Color(MultiValueEnum):
171
RED = 1, 'crimson', 'rouge', '#FF0000'
172
GREEN = 2, 'lime', 'forest', '#00FF00'
173
BLUE = 3, 'navy', 'azure', '#0000FF'
174
175
# Access by any value
176
print(Color(1)) # Color.RED
177
print(Color('crimson')) # Color.RED
178
print(Color('#FF0000')) # Color.RED
179
180
# Primary value is the first one
181
print(Color.RED.value) # 1
182
183
# Access all values
184
print(Color.RED._value_) # (1, 'crimson', 'rouge', '#FF0000')
185
```
186
187
### AddValueEnum
188
189
Enumeration that uses `_generate_next_value_` to prepend additional values to member definitions.
190
191
```python { .api }
192
class AddValueEnum(Enum):
193
def _generate_next_value_(name, start, count, last_values):
194
"""
195
Generate additional values to prepend to member definition.
196
197
Args:
198
name (str): Name of the enum member
199
start: Starting value
200
count (int): Number of existing members
201
last_values (list): Values from existing members
202
203
Returns:
204
Generated value to prepend
205
"""
206
```
207
208
#### Usage Example
209
210
```python
211
from aenum import AddValueEnum
212
213
class Planet(AddValueEnum):
214
def _generate_next_value_(name, start, count, last_values):
215
# Generate ID based on count
216
return count + 1
217
218
# Format: generated_id, mass, radius
219
MERCURY = 3.303e+23, 2.4397e6
220
VENUS = 4.869e+24, 6.0518e6
221
EARTH = 5.976e+24, 6.37814e6
222
223
def __init__(self, planet_id, mass, radius):
224
self.id = planet_id
225
self.mass = mass
226
self.radius = radius
227
228
print(Planet.EARTH.id) # 3
229
print(Planet.EARTH.mass) # 5.976e+24
230
```
231
232
### NoAliasEnum
233
234
Enumeration where duplicate values create distinct members instead of aliases, useful when you need separate enum members with the same value.
235
236
```python { .api }
237
class NoAliasEnum(Enum):
238
"""Enum where duplicate values create separate members."""
239
```
240
241
#### Usage Example
242
243
```python
244
from aenum import NoAliasEnum
245
246
class HttpStatus(NoAliasEnum):
247
OK = 200
248
SUCCESS = 200 # Separate member, not an alias
249
NOT_FOUND = 404
250
ERROR = 404 # Separate member, not an alias
251
252
print(HttpStatus.OK) # HttpStatus.OK
253
print(HttpStatus.SUCCESS) # HttpStatus.SUCCESS
254
print(HttpStatus.OK is HttpStatus.SUCCESS) # False
255
print(HttpStatus.OK == HttpStatus.SUCCESS) # True (same value)
256
```
257
258
### Specialized String Enums
259
260
#### LowerStrEnum
261
262
String enumeration that automatically converts member names to lowercase values.
263
264
```python { .api }
265
class LowerStrEnum(StrEnum):
266
"""StrEnum that uses lowercase member names as values."""
267
```
268
269
```python
270
from aenum import LowerStrEnum
271
272
class Command(LowerStrEnum):
273
START # Value becomes 'start'
274
STOP # Value becomes 'stop'
275
RESTART # Value becomes 'restart'
276
277
print(Command.START) # Command.START
278
print(Command.START.value) # 'start'
279
print(str(Command.START)) # 'start'
280
```
281
282
#### UpperStrEnum
283
284
String enumeration that automatically converts member names to uppercase values.
285
286
```python { .api }
287
class UpperStrEnum(StrEnum):
288
"""StrEnum that uses uppercase member names as values."""
289
```
290
291
```python
292
from aenum import UpperStrEnum
293
294
class LogLevel(UpperStrEnum):
295
debug # Value becomes 'DEBUG'
296
info # Value becomes 'INFO'
297
warning # Value becomes 'WARNING'
298
error # Value becomes 'ERROR'
299
300
print(LogLevel.debug.value) # 'DEBUG'
301
```
302
303
### Enum Settings
304
305
Configuration classes that modify enum behavior when used as base classes.
306
307
```python { .api }
308
class AddValue:
309
"""Setting that prepends values from _generate_next_value_."""
310
311
class MagicValue:
312
"""Setting that calls _generate_next_value_ when no args given."""
313
314
class MultiValue:
315
"""Setting that allows members to have multiple values."""
316
317
class NoAlias:
318
"""Setting that prevents aliasing of duplicate values."""
319
320
class Unique:
321
"""Setting that requires all values to be unique."""
322
```
323
324
#### Usage Example
325
326
```python
327
from aenum import Enum, AddValue, MultiValue, Unique
328
329
# Using settings as mixins
330
class ColorCode(Enum, MultiValue, Unique):
331
RED = 1, '#FF0000', 'red'
332
GREEN = 2, '#00FF00', 'green'
333
BLUE = 3, '#0000FF', 'blue'
334
# CRIMSON = 1, '#DC143C', 'crimson' # Would raise ValueError (Unique)
335
336
print(ColorCode('red')) # ColorCode.RED
337
print(ColorCode('#FF0000')) # ColorCode.RED
338
```
339
340
### Advanced Patterns
341
342
#### Custom Value Generation
343
344
```python
345
from aenum import Enum
346
347
class TimestampEnum(Enum):
348
def _generate_next_value_(name, start, count, last_values):
349
import time
350
return int(time.time() * 1000) # Millisecond timestamp
351
352
CREATED = () # Gets current timestamp
353
UPDATED = () # Gets current timestamp
354
ARCHIVED = () # Gets current timestamp
355
```
356
357
#### Complex Multi-Value Enums
358
359
```python
360
from aenum import MultiValueEnum
361
362
class HttpStatusCode(MultiValueEnum):
363
# Value, reason phrase, category
364
OK = 200, 'OK', 'success'
365
CREATED = 201, 'Created', 'success'
366
BAD_REQUEST = 400, 'Bad Request', 'client_error'
367
NOT_FOUND = 404, 'Not Found', 'client_error'
368
SERVER_ERROR = 500, 'Internal Server Error', 'server_error'
369
370
def __init__(self, code, phrase, category):
371
self.code = code
372
self.phrase = phrase
373
self.category = category
374
375
@property
376
def is_success(self):
377
return self.category == 'success'
378
379
@property
380
def is_error(self):
381
return 'error' in self.category
382
383
# Usage
384
status = HttpStatusCode(404)
385
print(status.phrase) # 'Not Found'
386
print(status.is_error) # True
387
388
# Access by any value
389
status = HttpStatusCode('Bad Request')
390
print(status.code) # 400
391
```
392
393
#### Ordered Multi-Value Enum
394
395
```python
396
from aenum import OrderedEnum, MultiValueEnum
397
398
class Priority(OrderedEnum, MultiValueEnum):
399
LOW = 1, 'low', 'minor'
400
MEDIUM = 2, 'medium', 'normal'
401
HIGH = 3, 'high', 'major'
402
CRITICAL = 4, 'critical', 'urgent'
403
404
# Comparison works with primary value
405
print(Priority.LOW < Priority.HIGH) # True
406
print(Priority('urgent') > Priority('low')) # True
407
408
# Access by any value
409
print(Priority('major')) # Priority.HIGH
410
print(Priority(2)) # Priority.MEDIUM
411
```
412
413
## Common Use Cases
414
415
### Version Numbering
416
417
```python
418
from aenum import OrderedEnum
419
420
class Version(OrderedEnum):
421
ALPHA = 1
422
BETA = 2
423
RC = 3
424
STABLE = 4
425
426
def can_upgrade(from_version, to_version):
427
return from_version < to_version
428
429
print(can_upgrade(Version.ALPHA, Version.STABLE)) # True
430
```
431
432
### State Machines with Validation
433
434
```python
435
from aenum import Enum, OrderedEnum
436
437
class WorkflowState(OrderedEnum):
438
DRAFT = 1
439
REVIEW = 2
440
APPROVED = 3
441
PUBLISHED = 4
442
ARCHIVED = 5
443
444
def can_transition_to(self, new_state):
445
# Only allow forward transitions or archiving
446
return new_state > self or new_state == WorkflowState.ARCHIVED
447
448
current = WorkflowState.DRAFT
449
print(current.can_transition_to(WorkflowState.REVIEW)) # True
450
print(current.can_transition_to(WorkflowState.PUBLISHED)) # True
451
print(current.can_transition_to(WorkflowState.DRAFT)) # False
452
```