Skip to content

Enumerations with enum

Beginning of the lesson

Enumerations with enum

Model a fixed set of choices as named constants instead of loose strings or numbers

Big Idea: An enumeration (an enum) is a class whose instances are a fixed, named set of constant values — think order statuses, user roles, traffic-light colours or card suits. Instead of scattering bare strings like "paid" or magic numbers like 2 through your code, you define them once as Status.PAID and let Python guarantee the set is closed, self-documenting and safe to compare.
By the end you will be able to:
  • explain why bare string/int constants are fragile,
  • define an enumeration with enum.Enum and read a member's .name and .value,
  • compare members safely with is and understand why members are singletons,
  • let Python assign values automatically with auto(),
  • reach for IntEnum when a member must also behave like an integer,
  • look a member up by value (Color(1)) or by name (Color['RED']) and iterate over the whole set.

1. The problem with bare constants

Fixed choice sets appear everywhere: an order is "pending", "paid" or "shipped"; a user is an "admin" or a "member". The naive approach is to write those values as plain strings or numbers directly in the code — so-called magic values.

status = "shiped"          # typo! nothing complains until later
if status == "shipped":    # never matches -> silent bug
    send_tracking_email()

Nothing catches the typo "shiped". The comparison quietly returns False and the email is never sent. Bare constants have three weaknesses:

  • No safety: any misspelled string is still a valid string, so mistakes surface at runtime, not when you write them.
  • No self-documentation: a stray 2 in if role == 2: tells the reader nothing about what 2 means.
  • No closed set: nothing stops another part of the program from inventing a fourth, unexpected status.

An enumeration fixes all three at once: the names are checked, they read like documentation, and the set of valid values is defined in exactly one place.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers