Enumerations with enum
Model a fixed set of choices as named constants instead of loose strings or numbers
enum) is a class whose instances are a fixed, named set of constant values — think order statuses, user roles, traffic-light colours or card suits. Instead of scattering bare strings like "paid" or magic numbers like 2 through your code, you define them once as Status.PAID and let Python guarantee the set is closed, self-documenting and safe to compare.
- explain why bare string/int constants are fragile,
- define an enumeration with
enum.Enumand read a member's.nameand.value, - compare members safely with
isand understand why members are singletons, - let Python assign values automatically with
auto(), - reach for
IntEnumwhen a member must also behave like an integer, - look a member up by value (
Color(1)) or by name (Color['RED']) and iterate over the whole set.
1. The problem with bare constants
Fixed choice sets appear everywhere: an order is "pending", "paid" or "shipped"; a user is an "admin" or a "member". The naive approach is to write those values as plain strings or numbers directly in the code — so-called magic values.
status = "shiped" # typo! nothing complains until later
if status == "shipped": # never matches -> silent bug
send_tracking_email()
Nothing catches the typo "shiped". The comparison quietly returns False and the email is never sent. Bare constants have three weaknesses:
- No safety: any misspelled string is still a valid string, so mistakes surface at runtime, not when you write them.
- No self-documentation: a stray
2inif role == 2:tells the reader nothing about what2means. - No closed set: nothing stops another part of the program from inventing a fourth, unexpected status.
An enumeration fixes all three at once: the names are checked, they read like documentation, and the set of valid values is defined in exactly one place.