Question presented to candidate:
"What does Python's enum module give you over plain constants like PENDING = 1, and how do Enum, IntEnum, StrEnum and Flag differ? When would you use one?"
What a strong answer should cover:
- An
Enumis a class whose members are a fixed set of named singleton objects with a.nameand a.value; members cannot be reassigned, iterate in definition order, and are looked up withStatus(2)orStatus["SHIPPED"] - Why it beats magic strings and module constants: typos fail loudly with
AttributeError, readablerepr, type checkers can verify exhaustivematch, and members carry methods and properties - Plain
Enummembers are not equal to their values (Status.SHIPPED == 2isFalse);IntEnumandStrEnum(3.11) are subclasses ofint/str, which helps interop (JSON, databases) but loses type safety auto(), aliases (two names with one value) versus@unique/@verify(UNIQUE), andFlag/IntFlagfor combinable bit flags with|andin- Version details:
enumarrived in 3.4 (PEP 435),autoandFlagin 3.6,StrEnum,ReprEnumandverifyin 3.11, which also changedformat()ofstr/intmixins;1 in StatusraisesTypeErroron 3.11 but returnsTrue/Falseon 3.12+ - When not to: open-ended or user-defined sets of values, or values loaded at runtime
Code / implementation expected: Optional β define an order-status enum, look members up from external values, and use it in match.