PythiloLesson 12 of 30 · progress kept in this browser

Enums

An enum is a fixed set of named constants. Each member has a name and a value, and a member is never mistaken for a plain string or number.

from enum import Enum, auto

class Status(Enum):
    DRAFT = auto()
    LIVE = auto()
    ARCHIVED = auto()

s = Status.LIVE
print(s, s.name, s.value)
print(Status["DRAFT"], Status(3))
print([m.name for m in Status])
print(s is Status.LIVE, s == 2)
  • Status["DRAFT"] looks a member up by name and Status(3) by value. Unknown input raises KeyError or ValueError.
  • Each member exists once, so is and == agree. Iteration follows definition order.
  • A member never equals its raw value: Status.LIVE == 2 is false. StrEnum and IntEnum members do equal their values, which helps when they travel through JSON or a database.
  • An enum can have methods, which receive the member as self.
  • Any name assigned in the class body becomes a member, so keep helper tables inside methods.
Your task

Write an enum Light with RED, YELLOW and GREEN, valued "red", "yellow" and "green", and a method next() that follows the cycle red, green, yellow, red. Write parse_light(text) returning the member whose value matches text ignoring case and surrounding spaces, or None.