Python 3D Academyবাংলা

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.GREEN always means the same one thing
  • a typo like Light.GREN is 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 like RED = 1
  • member: one choice, Light.RED, with a .name and a .value
  • lookup: Light(1) by value, Light["RED"] by name

Three ways to get a member, step by step:

  1. by its name in code: Light.RED
  2. by its value: Light(1), handy when the value comes from a file or a form
  3. 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)
A for loop goes through the members in the order they were written. print shows a member as Light.GREEN.

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) gives ValueError: 5 is not a valid Light.
  • A name that isn't a member. Light["PINK"] gives KeyError: 'PINK'.
  • Comparing a member with its value. Light.RED == 1 is False: 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

  1. What does this print?

    from enum import Enum
    
    class Size(Enum):
        SMALL = "S"
        LARGE = "L"
    
    print(Size.LARGE.name, Size.LARGE.value)
  2. What does this print?

    from enum import Enum
    
    class Light(Enum):
        RED = 1
        GREEN = 3
    
    print(Light(3), Light(3) == Light.GREEN)
  3. 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
  4. 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])
  5. Which line has a mistake?

    from enum import Enum
    
    class Light(Enum):
        RED = 1
        GREEN = 3
    
    print(Light(2))
  6. What does this print?

    from enum import StrEnum, auto
    
    
    class Status(StrEnum):
        OPEN = auto()
        CLOSED = auto()
    
    
    print(Status.OPEN, Status.CLOSED == "closed")

Coding tasks

  1. Write an Enum Light with RED = 1, AMBER = 2, GREEN = 3, and a function next_light(light) that gives the next one in the cycle: RED → GREEN → AMBER → RED.

  2. Write an Enum Size with SMALL = "S", MEDIUM = "M", LARGE = "L", and a function size_name(code) that turns a code like "M" into the member's name, "MEDIUM". An unknown code raises a ValueError, just as Size(code) does.

  3. Write an Enum Day with MON = 1 up to SUN = 7, and a function is_weekend(day) that returns True for SAT and SUN.