Course topics

By WebNest Studio Engineering Team

Python Tutorial

Enums in Python

Some values come from a small fixed set: order status (pending, paid, shipped), user role (student, instructor, admin), day of week. Using raw strings like "shiped" invites typos that no tool catches. An enumeration defines the allowed values once as named constants.

This lesson covers Enum, auto(), StrEnum and IntEnum, Flag for combinable permissions, adding methods to enums, and using enums with match.

Why it matters

Order statuses, user roles and days of the week have a fixed set of values. Representing them as bare strings invites typing mistakes that fail silently: "shiped" is a perfectly valid string. An enum gives each value a name, makes a wrong name an immediate error, and documents every allowed value in one place.

Defining and Using Enums

Subclass enum.Enum and list members as class attributes. Each member has a name and a value. Access members as Status.PAID, by value Status("paid") or by name Status["PAID"]. Members are singletons: compare with is or ==. Iterating the class yields members in definition order.

auto(), StrEnum and IntEnum

auto() assigns values automatically. StrEnum (3.11+) members are also strings — they serialise naturally to JSON and compare equal to their string values; with auto() the value is the lowercase member name. IntEnum members are integers. Plain Enum members are deliberately not equal to raw values, which catches mix-ups.

Flag for Combinations

enum.Flag members can be combined with | and tested with in — ideal for permissions: Permission.READ | Permission.WRITE.

Methods and Pattern Matching

Enums are classes, so they can have methods and properties, for example Status.can_cancel(). They work well with match statements to handle each state explicitly.

Examples

Defining, accessing and iterating an Enum

Python
from enum import Enum

class Status(Enum):
    PENDING = "pending"
    PAID = "paid"
    SHIPPED = "shipped"
    CANCELLED = "cancelled"

s = Status.PAID
print(s, s.name, s.value)
print(Status("shipped"), Status["PENDING"])
print([m.name for m in Status])
print(s is Status.PAID, s == "paid")
try:
    Status("shiped")
except ValueError as e:
    print("ValueError:", e)
Output
Status.PAID PAID paid
Status.SHIPPED Status.PENDING
['PENDING', 'PAID', 'SHIPPED', 'CANCELLED']
True False
ValueError: 'shiped' is not a valid Status

auto(), StrEnum, IntEnum and JSON

Python
import json
from enum import Enum, IntEnum, StrEnum, auto

class Color(Enum):
    RED = auto()
    GREEN = auto()

class Role(StrEnum):
    STUDENT = auto()
    ADMIN = auto()

class Priority(IntEnum):
    LOW = 1
    HIGH = 3

print(Color.RED.value, Color.GREEN.value)
print(Role.ADMIN, Role.ADMIN == "admin", json.dumps({"role": Role.STUDENT}))
print(Priority.HIGH > Priority.LOW, Priority.HIGH + 1, sorted([Priority.HIGH, Priority.LOW]))
Output
1 2
admin True {"role": "student"}
True 4 [<Priority.LOW: 1>, <Priority.HIGH: 3>]

Flag permissions, enum methods and match

Python
from enum import Enum, Flag, auto

class Permission(Flag):
    READ = auto()
    WRITE = auto()
    DELETE = auto()

editor = Permission.READ | Permission.WRITE
print(Permission.WRITE in editor, Permission.DELETE in editor)

class OrderStatus(Enum):
    PENDING = "pending"
    SHIPPED = "shipped"
    DELIVERED = "delivered"

    def can_cancel(self):
        return self is OrderStatus.PENDING

def message(status):
    match status:
        case OrderStatus.PENDING:
            return "We are preparing your order."
        case OrderStatus.SHIPPED:
            return "Your order is on the way."
        case OrderStatus.DELIVERED:
            return "Delivered. Enjoy!"

for st in OrderStatus:
    print(f"{st.value:<10} cancel={st.can_cancel()!s:<5} {message(st)}")
Output
True False
pending    cancel=True  We are preparing your order.
shipped    cancel=False Your order is on the way.
delivered  cancel=False Delivered. Enjoy!

Common Mistakes

  • Comparing plain Enum members with raw strings (Status.PAID == "paid" is False) — use StrEnum or .value.
  • Using magic strings and numbers instead of enums for fixed sets of values.
  • Defining two members with the same value, which silently creates an alias; use @enum.unique to prevent it.
  • Storing enum names in a database and later renaming members.

Exercise

Define an enum Status with the members PENDING, PAID and SHIPPED, with the values 1, 2 and 3. Print the name and value of PAID, the member whose value is 1, and the names of all members.

Expected output: PAID 2, Status.PENDING, ['PENDING', 'PAID', 'SHIPPED'] (one per line)

Python · starter code
from enum import Enum


# TODO: enum Status with PENDING = 1, PAID = 2, SHIPPED = 3


# TODO: print the name and the value of Status.PAID
# TODO: print the member that has the value 1
# TODO: print a list of the names of all members
Show hints
  • Each member has .name and .value. Calling the enum with a value, as in Status(1), returns the member.
  • An enum can be looped over: [member.name for member in Status].
Show solution
Python · solution
from enum import Enum


class Status(Enum):
    PENDING = 1
    PAID = 2
    SHIPPED = 3


print(Status.PAID.name, Status.PAID.value)
print(Status(1))
print([member.name for member in Status])

Quick quiz

1. What does Status(99) do when no member has the value 99?

  • A. Returns None
  • B. Raises ValueError
  • C. Creates a new member
  • D. Returns the first member
Show answer

B. An invalid value is rejected immediately, which is one of the benefits of an enum.

2. What does auto() do in an enum?

  • A. Makes the enum mutable
  • B. Sorts the members
  • C. Assigns a value automatically
  • D. Creates aliases
Show answer

C. It is used when the particular values do not matter.

3. With a plain Enum, what does Status.PAID == 2 return?

  • A. True
  • B. 2
  • C. It raises an error
  • D. False
Show answer

D. A member is not equal to its value. Compare members with each other, or use IntEnum.

Interview questions

Why use an Enum instead of string or integer constants?

Show answer

An enum restricts a value to a defined set, so a misspelled name raises an error where a misspelled string would pass unnoticed. The members can be listed and looped over, they print with meaningful names, editors can autocomplete them, and type checkers can verify them. Members are also singletons, so they are compared with is.

What is the difference between Enum, IntEnum and StrEnum?

Show answer

Members of a plain Enum are not equal to their values. Members of an IntEnum are also integers, and members of a StrEnum, added in Python 3.11, are also strings, so they compare equal to raw values and can be passed where an integer or string is expected, which is convenient for JSON and database values. The plain Enum is stricter and is the default choice.

Key Points to Remember

  • Enums define named constants for fixed sets of values.
  • Access members by attribute, value or name; iterate the class.
  • auto() generates values; StrEnum and IntEnum behave like str/int.
  • Flag supports combinable options with | and in.
  • Enums can have methods and work naturally with match.

Practice in the playground

Write and run your own code for this topic, or start from the exercise or an example. Runs Python in your browser. Your code for each topic is kept in this browser.

Run the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.

WebNest Studio

Written by

WebNest Studio Engineering Team

Practical lessons from developers working with Java, Python, React, databases and production systems.

Led by Vansh Duggal, Founder, WebNest Studio · Full-stack & software engineering