Lesson · Dataclasses, Enums & Data Modeling
Enums
55 min readEnums
Enums give a domain a finite set of named values. They replace magic constants with types that communicate valid states and can carry behavior when needed.
Learning goals
- Define an
Enumclass and explain why each member is a singleton. - Use
auto()to assign values and read.nameand.valueoff a member. - Iterate an enum class, look members up by value and by name, and predict what each returns.
- Explain how
IntEnumdiffers fromEnumwhen comparing against plain integers. - Replace scattered status constants with an enum and say what the type adds at a boundary.
Mental model
The fence maps the whole vocabulary onto one idea: the class is the type, its attributes are the members, and each member is a singleton, which is why status is Status.NEW is True and why iteration lists the members in definition order. auto() exists so the values do not have to be meaningful, and IntEnum is the variant that additionally lets members stand in wherever an int is expected.
Mental model
read it top to bottom
Enum a closed set of named singletons, one instance per member auto() fills in distinct values so you do not hand-number them members reached by attribute (Status.NEW), by value (Status(1)), or in order (iteration) checks identity is exact, equality follows the type, and only IntEnum compares as int
Core idea
An enum is a class whose instances are fixed: every attribute named at class creation becomes one singleton member, and nothing else can construct another. The worked example's Status gives three states through auto(), and both printed lines lean on member properties: status is Status.NEW is true because members are singletons, and iterating Status yields members in definition order. The type's job is domain modeling: a function that takes Status cannot receive a typo, because no other values of that type exist.
Enum
Enum defines a finite set of named singleton members. Comparing enum members directly is clearer than comparing magic strings or integers spread through an application.
IntEnum
IntEnum is an Enum whose members also subclass int, so a member can be passed anywhere an integer is accepted and Status.RUNNING == 2 is True. It exists for interoperability with integer-based APIs, flags, and libraries that demand real ints. The cost is that comparisons against arbitrary integers succeed, so foreign values blend in more easily than with a plain Enum.
auto
auto() delegates each member's value to the enum machinery, which assigns distinct integers in definition order (1, 2, 3, and so on). It is the right default when the numeric values carry no meaning, since the names are the interface. Explicit values are for cases where existing numbers must be preserved, such as protocol codes.
Members
Members are the singleton instances created during class definition: every assignment in the enum body becomes exactly one member, and the class carries lookup, iteration, and name/value access for them. .name and .value expose the two halves of each member, with values set by auto() or by explicit assignment. Aliases collapse during iteration, so __members__ and the visible member list can differ.
Comparison
Enum members compare like singletons: == between members of the same class is effectively an identity check, two members of different enum classes never compare equal, and plain Enum members do not compare against their raw values at all. Ordering does not exist for plain enums, so Status.NEW < Status.DONE raises TypeError. The exception is IntEnum, whose members are integers and inherit integer comparison.
Iteration
Iterating an enum class yields its members in definition order, skipping aliases; list(Status) returns the members themselves, while comprehensions over them usually read .name or .value. __members__ gives the full name-to-member mapping when aliases matter. The worked example's comprehension turns the class into ['NEW', 'RUNNING', 'DONE'].
Domain modeling
A domain-modeling type makes invalid states hard to express: a function annotated with Status accepts only Status members, so a typo fails at the boundary instead of flowing through as a loose string. Enums also group related constants under one name and give them a shared home for methods and documentation. The worked example replaces what would otherwise be three scattered constants with one type.
Walkthrough
class Status(Enum)with three assignments creates exactly three members;auto()hands each a distinct value in definition order, soStatus.NEW.valueis 1 without any hand-numbering.status = Status.NEWbinds the singleton member, soprint(status is Status.NEW)printsTrue: the class keeps exactly one instance per member and attribute access returns it.- Iterating the class itself, as the list comprehension does, walks the members in definition order and collects
.namestrings, printing['NEW', 'RUNNING', 'DONE']. - Predict before running: the lines
Trueand['NEW', 'RUNNING', 'DONE'], and whatStatus.NEW == 1prints (False, because a plainEnummember is not an int).
Experiments to try
- Print
Status.RUNNING.nameandStatus.RUNNING.value, then callStatus(2)andStatus["RUNNING"]; explain which lookup uses the value and which uses the name. - Add a fourth member and rerun the comprehension; confirm the order follows the class body.
- Try
Status(99)and read theValueError; then tryStatus["MISSING"]and read theKeyError. Explain which lookup produces which error. - Switch the class to
IntEnumand checkStatus.NEW == 1andStatus.RUNNING == 2; state what the members gained and what ambiguity they accepted.
Common mistakes
- Comparing an
Enummember to its value, as inStatus.NEW == 1, and expectingTrue: plain enums do not compare against raw values, and onlyIntEnumchanges that. - Giving two members the same value: in a plain
Enumthe second name becomes an alias for the first, so iteration skips it and.namereports the first name. - Trying to extend an enum by subclassing: adding members to a subclass raises
TypeError, because the set of members is fixed at class creation. - Storing a member's value in a database or API and comparing the fetched int against members directly; convert once at the boundary with
Status(value)and keep the enum type inside.
Practice: Easy
- Run the worked example and record both printed lines; then print
Status.NEW.nameandStatus.NEW.valueand explain whatauto()assigned. - Add a
FAILED = auto()member and rerun the comprehension; record the new list and explain where the order comes from. - Run
Status.NEW is Status.NEWandStatus.NEW == Status(1); explain each result with singleton and equality rules.
Practice: Medium
- Define a
Priorityenum with LOW, MEDIUM, and HIGH, then write a function that handles all three members and rejects anything else throughPriority(...)at its boundary. - Change
StatusfromEnumtoIntEnumand note which comparisons against plain integers flip toTrue; list one place where the flexibility helps and one where it hides a mistake. - Give
Statusa method such aslabel()returning a human-readable string per member; check that methods coexist with members and thatStatus.DONE.label()works.
Practice: Hard
- Design a
RetryPolicyenum whose members carry behavior through ashould_retry()method; test every member and show that no other values of the type can exist. - Build a failure lab:
Status.NEW == 1returningFalseand the silent bug it causes inside anif; two members that share a value and the alias behavior; a subclass attempt that raisesTypeError. Explain each mechanism and the fix. - Connect this lesson to serialization: store
Status.NEWas its value and as its name, reconstruct each withStatus(...)andStatus[...], and say which pair survives a decision to renumber the members.
Lesson checklist
- I can define an enum with
auto()and read.nameand.valueoff a member. - I can explain why
Status.NEW is Status.NEWisTrueand what singleton members mean. - I can look a member up by value and by name and name the exception for a failed lookup.
- I can say what
IntEnumadds and when that is helpful versus risky.
Remember
An enum is a class with a fixed cast: every member is a singleton created at class definition, reachable by attribute, by value, or in definition order, and no other instances exist. The worked example's `Status` builds three states with `auto()` and shows the two everyday facts, identity checks work on members and iteration lists them in order. Use enums to make valid states a type; use `IntEnum` only where integer compatibility is genuinely needed.
Interview angles
What is the main purpose of **Enum**?+
Enum defines a finite set of named singleton members. Comparing enum members directly is clearer than comparing magic strings or integers spread through an application.
What should you pay attention to when using **IntEnum**?+
IntEnum is an Enum whose members also subclass int: they can be passed anywhere an integer is accepted, and comparisons against plain integers work. The worked example uses plain Enum, so Status.NEW == 1 is False; switching to IntEnum makes it True as well as ordering members like numbers.
How does **auto** fit into this lesson?+
auto() asks the enum machinery to choose each member's value, assigning distinct integers in definition order. In the worked example it fills NEW, RUNNING, and DONE with 1, 2, and 3, so the names stay the source of truth and .value reports what was assigned.
What happens when two members are given the same value in a plain `Enum`?+
The second name becomes an alias for the first member rather than a new one: .name still reports the first name, and iterating the class yields the member once. Duplicate values are easy to miss unless you inspect __members__.