How to Use IntEnum Arithmetic for Priority Levels in Python
Demonstrates Python IntEnum arithmetic for priority levels, showing how enum members behave like integers in calculations and comparisons.
Python code
20 linesfrom enum import IntEnum
class Priority(IntEnum):
LOW = 1
MEDIUM = 5
HIGH = 10
CRITICAL = 20
if __name__ == "__main__":
current = Priority.MEDIUM
boosted = current + 3
lowered = current - 2
doubled = current * 2
print(f"Current: {current} ({current.value})")
print(f"Boosted (+3): {boosted} ({boosted.value})")
print(f"Lowered (-2): {lowered} ({lowered.value})")
print(f"Doubled (*2): {doubled} ({doubled.value})")
print(f"Can compare: {current > Priority.LOW}")
print(f"Works with range: {list(range(Priority.LOW, Priority.HIGH + 1))}")
Output
Current: MEDIUM (5)
Boosted (+3): 8 (8)
Lowered (-2): 3 (3)
Doubled (*2): 10 (10)
Can compare: True
Works with range: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
How it works
IntEnum makes each member an actual int subclass, so arithmetic operators like +, -, and * return plain integers (not IntEnum instances). This is handy when you need numeric computations on enum values, though you lose the enum name after arithmetic. The if __name__ == "__main__": guard ensures the demo runs only when executed directly. Comparisons work naturally because enum members are also integers, enabling use with range and other numeric operations.
Common mistakes
- Assuming arithmetic results remain `IntEnum` members (they become plain ints)
- Forgetting to import `IntEnum` (using `Enum` instead, which does not support arithmetic)
- Expecting `Priority.MEDIUM + 3` to yield `Priority.HIGH` if 8 existed; it doesn't auto-map to enum values
Variations
- Use a custom `__add__` method on a regular `Enum` to return enum members for arithmetic
- Use `enum.auto()` to assign sequential values automatically
Real-world use cases
- Escalating a support ticket priority by adding a delta to the current `Priority` enum value.
- Calculating resource allocation levels by weighting multiple `Priority` values in a scoring formula.
- Filtering tasks by priority ranges in a scheduler using `range(Priority.LOW, Priority.HIGH + 1)`.
Sponsored
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.