Enum: a fixed set of choices
🌍 In real life. A traffic light can only be red, amber or green. A T-shirt comes in S, M or L. There is no colour "purple-ish" and no size "medim".
If a program stores these as plain text, a typo like "gren" slips through quietly and causes a bug much later. An Enum (short for enumeration, a numbered list) is a class whose members are the only allowed choices:
Light.GREENalways means the same one thing- a typo like
Light.GRENis an error straight away
The idea in one sentence: an Enum is a class whose members are the only allowed choices, so a typo becomes an error right away instead of a hidden bug.
Its words:
- Enum:
class Light(Enum):with members likeRED = 1 - member: one choice,
Light.RED, with a.nameand a.value - lookup:
Light(1)by value,Light["RED"]by name
Three ways to get a member, step by step:
- by its name in code:
Light.RED - by its value:
Light(1), handy when the value comes from a file or a form - by its name as text:
Light["RED"]
Every member knows its .name ('RED') and its .value (1). Members are compared by which member they are: Light(1) == Light.RED is True. A value or name that isn't there raises an error, which is exactly the protection you want:
from enum import Enum
class Light(Enum):
RED = 1
AMBER = 2
GREEN = 3
for light in Light:
print(light.name, light.value)
now = Light.GREEN
if now == Light.GREEN:
print("Go!")
print(now)Letting Python number them: auto(). When the values don't matter, only the choices do, write SMALL = auto(): the members get 1, 2, 3… in order, and you can't give two of them the same number by mistake.
Enums that are also text or numbers. A plain Enum member is not its value (Light.RED == 1 is False). Sometimes you want it to be: a StrEnum member is a string, so it can go straight into JSON or a database, and with auto() its value is its name in lower case. An IntEnum member is an int, so it can be compared with and added to numbers.
from enum import Enum, IntEnum, StrEnum, auto
class Size(Enum):
SMALL = auto()
MEDIUM = auto()
LARGE = auto()
class Colour(StrEnum):
RED = auto()
GREEN = auto()
class Floor(IntEnum):
GROUND = 0
FIRST = 1
print([s.value for s in Size])
print(Colour.RED, Colour.RED == "red", Colour.RED.upper())
print(Floor.FIRST + 1, Floor.FIRST < 2)Mistakes and edge cases.
- A value that isn't a member.
Light(5)givesValueError: 5 is not a valid Light. - A name that isn't a member.
Light["PINK"]givesKeyError: 'PINK'. - Comparing a member with its value.
Light.RED == 1isFalse: a member isn't its value. Compare members with members, or use.value. - Changing a member. Members are fixed once the class is made.
Quiz
What does this print?
from enum import Enum class Size(Enum): SMALL = "S" LARGE = "L" print(Size.LARGE.name, Size.LARGE.value)What does this print?
from enum import Enum class Light(Enum): RED = 1 GREEN = 3 print(Light(3), Light(3) == Light.GREEN)Why use an Enum instead of plain strings like
"red"?- Only the listed members exist, so a typo is an error straight away
- Enums run faster than strings
- Enums can hold any value at all
What does this print?
from enum import Enum class Day(Enum): MON = 1 TUE = 2 WED = 3 print(len(Day), [d.name for d in Day])Which line has a mistake?
from enum import Enum class Light(Enum): RED = 1 GREEN = 3 print(Light(2))What does this print?
from enum import StrEnum, auto class Status(StrEnum): OPEN = auto() CLOSED = auto() print(Status.OPEN, Status.CLOSED == "closed")
Coding tasks
Write an Enum
LightwithRED = 1,AMBER = 2,GREEN = 3, and a functionnext_light(light)that gives the next one in the cycle: RED → GREEN → AMBER → RED.Write an Enum
SizewithSMALL = "S",MEDIUM = "M",LARGE = "L", and a functionsize_name(code)that turns a code like"M"into the member's name,"MEDIUM". An unknown code raises a ValueError, just asSize(code)does.Write an Enum
DaywithMON = 1up toSUN = 7, and a functionis_weekend(day)that returns True for SAT and SUN.