Reading history

Python Enum: Enum, StrEnum, IntEnum and Flag

6 min read 0 views

Create Python enumerations: names and values, lookups, auto(), methods, StrEnum, IntEnum, Flag for permissions, @unique and enums in match-case.

An enumeration, or enum, is a fixed set of named values, such as the stages of an order or the seasons of the year. Using OrderStatus.PAID instead of the number 2 or the string “paid” makes code easier to read and stops typing mistakes, because a misspelt member name raises an error straight away. Python’s built-in enum module provides Enum and several useful variations.

In this lesson you will learn

  • Creating an Enum and reading name and value
  • Looking up members by value and by name
  • Automatic values with auto() and methods on enums
  • StrEnum, IntEnum and Flag
  • Preventing duplicate values with @unique

You should know classes and objects and the match-case statement.

Creating and Using an Enum

from enum import Enum, auto

class OrderStatus(Enum):
    PENDING = 1
    PAID = 2
    SHIPPED = 3
    DELIVERED = 4

s = OrderStatus.PAID
print(s, "|", s.name, "|", s.value)
print(repr(s))
print("by value:", OrderStatus(3))
print("by name:", OrderStatus["DELIVERED"])
print("is paid?", s is OrderStatus.PAID)
print("all:", [m.name for m in OrderStatus])

# Members are not plain numbers
print("PAID == 2?", s == 2)

try:
    OrderStatus(9)
except ValueError as e:
    print("ValueError:", e)

# auto() picks values for you; methods can live on the enum
class Season(Enum):
    SUMMER = auto()
    MONSOON = auto()
    AUTUMN = auto()
    LATE_AUTUMN = auto()
    WINTER = auto()
    SPRING = auto()

    def next(self):
        members = list(Season)
        return members[(members.index(self) + 1) % len(members)]

print([(m.name, m.value) for m in Season][:3], "...")
print("after SPRING comes", Season.SPRING.next().name)

match s:
    case OrderStatus.PENDING:
        print("Waiting for payment")
    case OrderStatus.PAID | OrderStatus.SHIPPED:
        print("On its way soon")
    case _:
        print("Done")

Output

OrderStatus.PAID | PAID | 2
<OrderStatus.PAID: 2>
by value: OrderStatus.SHIPPED
by name: OrderStatus.DELIVERED
is paid? True
all: ['PENDING', 'PAID', 'SHIPPED', 'DELIVERED']
PAID == 2? False
ValueError: 9 is not a valid OrderStatus
[('SUMMER', 1), ('MONSOON', 2), ('AUTUMN', 3)] ...
after SPRING comes SUMMER
On its way soon
  • An enum is written like a class whose body lists the members. Each member has a name (“PAID”) and a value (2).
  • OrderStatus(3) finds a member by its value, and OrderStatus["DELIVERED"] finds one by its name. An unknown value raises ValueError, which is a good way to check data coming from a file or a form.
  • Each member exists only once, so you can compare with is. Looping over the enum gives the members in the order they were written.
  • A plain Enum member is not equal to its value: OrderStatus.PAID == 2 is False. This stops an order status being mixed up with an ordinary number by accident.
  • auto() numbers the six seasons of Bangladesh for you, starting at 1. The next method shows that an enum can have methods like any class; after the last season it wraps round to the first.
  • Enum members work well in match, as long as you write the full dotted name such as OrderStatus.PENDING.

StrEnum, IntEnum, Flag and unique

from enum import Enum, IntEnum, StrEnum, Flag, auto, unique

# StrEnum members ARE strings: handy for JSON, URLs and databases
class Currency(StrEnum):
    BDT = "BDT"
    USD = "USD"

print(Currency.BDT == "BDT", f"price in {Currency.USD}", Currency("BDT").upper())

# IntEnum members ARE ints: they compare and sort like numbers
class Priority(IntEnum):
    LOW = 1
    MEDIUM = 2
    HIGH = 3

tasks = [("backup", Priority.LOW), ("fix login", Priority.HIGH), ("reply mail", Priority.MEDIUM)]
for name, p in sorted(tasks, key=lambda t: t[1], reverse=True):
    print(f"  {p.name:<6} {name}")
print("HIGH > 2?", Priority.HIGH > 2)

# Flag: members combine with | like permission bits
class Perm(Flag):
    READ = auto()
    WRITE = auto()
    DELETE = auto()

editor = Perm.READ | Perm.WRITE
print("editor:", editor)
print("can write?", Perm.WRITE in editor, "| can delete?", Perm.DELETE in editor)
admin = editor | Perm.DELETE
print("admin values:", [p.name for p in admin])

# unique: refuse two names for the same value
try:
    @unique
    class Grade(Enum):
        A = 5
        A_PLUS = 5
except ValueError as e:
    print("ValueError:", e)

# Without @unique the second name becomes an alias
class Size(Enum):
    MEDIUM = "M"
    M = "M"
print("alias:", Size.M, "| members:", [s.name for s in Size])

Output

True price in USD BDT
  HIGH   fix login
  MEDIUM reply mail
  LOW    backup
HIGH > 2? True
editor: Perm.READ|WRITE
can write? True | can delete? False
admin values: ['READ', 'WRITE', 'DELETE']
ValueError: duplicate values found in <enum 'Grade'>: A_PLUS -> A
alias: Size.MEDIUM | members: ['MEDIUM']
  • StrEnum (Python 3.11 and later) members are real strings, so Currency.BDT == "BDT" is True and string methods such as upper() work. This is convenient when values are saved to JSON, a database or a URL.
  • IntEnum members are real integers, so they sort and compare with numbers. Here tasks are listed from highest to lowest priority.
  • Flag members can be combined with |, like permission switches. in asks whether a combination includes a member, and looping over a combination lists its parts.
  • Normally two names with the same value are allowed: the second becomes an alias for the first and does not appear when you loop. @unique turns this into an error, which catches copy-and-paste mistakes.

Which Enum Type?

TypeMembers behave likeGood for
EnumTheir own type onlyStatuses, modes, choices
StrEnumStringsValues stored as text: JSON, databases, settings
IntEnumIntegersLevels and priorities that must compare with numbers
FlagCombinable bitsPermissions and option sets

Common Mistakes

  1. Comparing an Enum member with its raw value, such as status == 2. Compare with the member, or use status.value.
  2. Trying to change a member, as in OrderStatus.PAID = 5. Enum members are fixed and this raises an error.
  3. Writing case PAID: in a match. A bare name captures any value; use case OrderStatus.PAID:.
  4. Saving the member itself to JSON. Save member.value (or use StrEnum) and rebuild it with OrderStatus(value).

Practice Exercises

Exercise 1. Create an enum Day for the seven days of the week and a method is_weekend() that returns True for Friday and Saturday.

Show answer
from enum import Enum, auto

class Day(Enum):
    SAT = auto(); SUN = auto(); MON = auto(); TUE = auto()
    WED = auto(); THU = auto(); FRI = auto()

    def is_weekend(self):
        return self in (Day.FRI, Day.SAT)

print(Day.FRI.is_weekend(), Day.MON.is_weekend())   # True False

Exercise 2. Using the Perm flag from the lesson, write a function that returns True only if a user has both READ and DELETE.

Show answer
def can_clean_up(perms):
    needed = Perm.READ | Perm.DELETE
    return needed in perms

print(can_clean_up(Perm.READ | Perm.WRITE))                # False
print(can_clean_up(Perm.READ | Perm.WRITE | Perm.DELETE))  # True

Frequently Asked Questions

Why not just use constants such as PAID = 2?

Plain constants are only numbers, so nothing stops you passing 7 or mixing a status with a quantity. An enum groups related values, prints readable names, can be looped over, and rejects unknown values.

Can enum members hold more than one value?

Yes. Give each member a tuple and unpack it in __init__, for example SMALL = ("S", 250) with def __init__(self, code, ml). Each member then has its own attributes.

Summary

  • An enum is a fixed set of named values with name and value.
  • Look up members with Enum(value) or Enum["NAME"].
  • StrEnum and IntEnum act like strings and integers; Flag members combine.
  • @unique rejects duplicate values.

Next: Python SQLite3 Database.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *