Skip to the solution
EasyBackend10 min read

What is the enum module and when should you use it?

985 views

The problem

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 Enum is a class whose members are a fixed set of named singleton objects with a .name and a .value; members cannot be reassigned, iterate in definition order, and are looked up with Status(2) or Status["SHIPPED"]
  • Why it beats magic strings and module constants: typos fail loudly with AttributeError, readable repr, type checkers can verify exhaustive match, and members carry methods and properties
  • Plain Enum members are not equal to their values (Status.SHIPPED == 2 is False); IntEnum and StrEnum (3.11) are subclasses of int/str, which helps interop (JSON, databases) but loses type safety
  • auto(), aliases (two names with one value) versus @unique / @verify(UNIQUE), and Flag / IntFlag for combinable bit flags with | and in
  • Version details: enum arrived in 3.4 (PEP 435), auto and Flag in 3.6, StrEnum, ReprEnum and verify in 3.11, which also changed format() of str/int mixins; 1 in Status raises TypeError on 3.11 but returns True/False on 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.

  • enum
  • stdlib

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 10 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonEnum, auto, aliases, IntEnum, StrEnum, Flag and enums with methods
PythonEnums in real code: match/case, _missing_, JSON, verify and gotchas

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 9 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextEasy

How do break, continue, pass and loop else work?

Continue