💡 Python QuickBits — 🔢 Smarter Enums with auto()


Description:

Enums are a great way to give readable names to constant values. But manually assigning numbers is repetitive and prone to mistakes. Python’s auto() fixes this by assigning values automatically.


The Manual Way

Traditionally, you define enums with explicit values:

from enum import Enum

class StatusManual(Enum):
    PENDING = 1
    IN_PROGRESS = 2
    COMPLETED = 3

for s in StatusManual:
    print(s, s.value)

This works — but if you reorder or insert items, you must renumber everything.


The Smarter Way with auto()

With auto(), Python automatically assigns values in order, starting at 1 by default:

from enum import Enum, auto

class StatusAuto(Enum):
    PENDING = auto()
    IN_PROGRESS = auto()
    COMPLETED = auto()

for s in StatusAuto:
    print(s, s.value)

Now, you can add or reorder items without touching numbers.


Mixing Custom and Auto Values

You can also combine explicit values with auto(). Auto continues counting from the last manual value:

class Priority(Enum):
    LOW = 1
    MEDIUM = auto()   # becomes 2
    HIGH = auto()     # becomes 3

for p in Priority:
    print(p, p.value)

Key Points

  • auto() saves you from hardcoding values.
  • Easy to insert or reorder enum members.
  • Works seamlessly with explicit values.
  • Clean, Pythonic, and built into the standard library.

Code Snippet:

from enum import Enum, auto   # Enum base class and auto() helper for auto values


class StatusManual(Enum):
    PENDING = 1        # manually assign each constant
    IN_PROGRESS = 2    # tedious if list is long
    COMPLETED = 3      # easy to break if you reorder items

print("Manual Enums:")
for s in StatusManual:
    print(s, s.value)   # show both name and value


class StatusAuto(Enum):
    PENDING = auto()       # gets value 1 automatically
    IN_PROGRESS = auto()   # becomes 2
    COMPLETED = auto()     # becomes 3

print("\nAuto Enums:")
for s in StatusAuto:
    print(s, s.value)      # each has auto-assigned value


class Priority(Enum):
    LOW = 1          # explicitly set value
    MEDIUM = auto()  # auto() continues → 2
    HIGH = auto()    # auto() continues → 3

print("\nPriority Enums:")
for p in Priority:
    print(p, p.value)

Link copied!

Comments

Add Your Comment

Comment Added!