QA
Intermediate LevelPython

How do you create type-safe enumerated constants using Enum, IntEnum, and @unique in Python?

❓ Interview Prompt: Explain `enum.Enum`, `auto()`, `@unique` decorator, `IntEnum`, and type-safe constant domain modeling.

Python's 'enum' module allows creating strongly-typed enumerated constants:

Key Features:

•
'auto()': Automatically assigns sequential integer values.
•
'@unique': Decorator that guarantees no two enum members share identical values.
•
Prevents magic strings and bugs caused by invalid domain values!

Code Implementation Example

python
from enum import Enum, auto, unique

@unique
class OrderStatus(Enum):
    PENDING = auto()
    PROCESSING = auto()
    SHIPPED = auto()
    DELIVERED = auto()

current_status = OrderStatus.PENDING
if current_status == OrderStatus.PENDING:
    print('Order is pending processing')
💡Creating type-safe unique enumeration constants using Enum.
🎯 Interview Key Takeaway

Use Enum constants to eliminate magic strings and enforce type-safe domain state values.

#Enum#auto()#@unique#Type Safety#Intermediate
Back to all Python Questions→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?