Skip to content
Tutorials Center
My learning

Topics

Lesson 81 of 149 ยท Object-Oriented Programming

Enums

Replace magic strings and numbers with Python enums. Learn Enum, auto(), StrEnum, IntEnum, Flag, looking up members, adding methods and using enums in match.

Imagine an order system where the status is stored as a string: "pending", "shipped", "delivered". Sooner or later someone writes "shiped" or "Delivered", and the bug hides quietly until a customer complains. Plain strings and numbers that carry special meaning are called magic values, and they're a common source of mistakes.

An enumeration (enum) is a fixed set of named constants. With the enum module, OrderStatus.SHIPPED is a real object: a typo becomes an immediate AttributeError, your editor can autocomplete the options, and the code documents exactly which values are allowed.

Creating an enum

Subclass Enum and list the members as class attributes. Each member has a name and a value:

Python A first enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Member names are written in UPPER_CASE because they're constants. Each member is a single, unique object, so you compare members with is (or ==; both work). Members can't be reassigned or added later; the set is fixed when the class is defined.

Looking up members

You'll often get a raw value from outside your program, such as a number from a database or a string from a form or JSON, and need the matching member. Call the enum with a value, or index it with a name:

Python Value and name lookup

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

An unknown value raises ValueError and an unknown name raises KeyError, so bad input is caught at the border of your program instead of spreading inside it.

Warning: A plain Enum member is not equal to its value: Size.SMALL == "S" is False. Compare members with members, or convert the raw value first with Size("S"). If you need members that also behave like strings or ints, use StrEnum or IntEnum (below).

auto() values

When the actual values don't matter, only the names, let auto() pick them. For a plain Enum it numbers members 1, 2, 3 and so on:

Python auto()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Using auto() also signals to readers that no code should depend on the specific numbers.

StrEnum and IntEnum

Sometimes members need to act like their values: sending them to an API, writing them to a file, or comparing them with data from elsewhere. StrEnum (Python 3.11+) makes members real strings, and IntEnum makes them real ints:

Python StrEnum and IntEnum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With StrEnum, auto() produces the member name in lowercase, which is usually exactly the string you want. Because members are strings, they work in f-strings, json.dumps(), string methods and comparisons. IntEnum members can be compared and sorted like numbers.

Use them when you need that interoperability. Otherwise prefer plain Enum: it's stricter, so a stray "shipped" string can't sneak into places that expect a status.

Adding methods and properties

An enum is a class, so it can have methods and properties. This keeps behavior that depends on the member right next to the definition:

Python Enums with methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

When a member's value is a tuple, Python passes its items to the enum's __init__, so each member can carry several pieces of data.

Enums in match statements

Enums and pattern matching are a natural pair. Dotted names such as Signal.RED are value patterns, so each case compares against that member:

Python match with an enum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Always write case Signal.RED: with the class name. A bare case RED: would be a capture pattern that matches anything and binds it to a new variable called RED. Type checkers like mypy can also warn you when a match over an enum forgets a member.

Aliases and unique values

If two members share the same value, the second one becomes an alias for the first rather than a separate member. That's occasionally useful, for example letting Color.GREY be another spelling of Color.GRAY, but more often it's a copy-paste mistake. Iterating over the enum skips aliases, and the @unique decorator from the enum module turns duplicate values into an error when the class is defined:

Python
from enum import Enum, unique

@unique
class Level(Enum):
    LOW = 1
    MEDIUM = 2
    HIGH = 2   # ValueError: duplicate values found in <enum 'Level'>: HIGH -> MEDIUM

Storing and loading enums

Enums live inside your program, but data on disk or on the network is made of strings and numbers. The usual approach is to store member.value (or member.name) and rebuild the member when reading, with Status(value) or Status[name]. Storing the value is the common choice, because you can then rename a member in code without breaking saved data. With StrEnum and IntEnum, saving needs no conversion at all, since the members already are strings or ints.

Flags: combining members

Flag is for options that can be combined, like file permissions or text styles. Members are combined with | and tested with in:

Python Flag

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

auto() gives flag members powers of two (1, 2, 4, ...), so each combination maps to a unique number.

When to use an enum

Reach for an enum whenever a value must be one of a small, known set of options that you'd otherwise spell as strings or numbers scattered through the code: statuses, roles, directions, sizes, log levels, card suits, game states. Good signs are a comment like # can be "draft", "review" or "published", or a chain of if statements comparing against the same handful of strings.

Enums are a poor fit when the set of options changes often or comes from users or a database at runtime, such as product categories that staff can edit. Those belong in data, not in code. And when you only need one or two unrelated constants, a module-level name like MAX_RETRIES = 3 is simpler.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given class Size(Enum): SMALL = "S", how do you get the member from the string "S"?

    Calling the enum looks up by value. Square brackets look up by name, so Size["SMALL"] would also work.
  2. 2. What is Size.SMALL == "S" for a plain Enum?

    Plain enum members are not equal to their values. Use StrEnum if members should compare equal to strings.
  3. 3. In a StrEnum, what value does PENDING = auto() get?

    For StrEnum, auto() uses the lowercase member name as the value.
  4. 4. Why write case Color.RED: instead of case RED: in a match statement?

    A bare name in a case is a capture pattern. Dotted names are value patterns that compare against the member.
  5. 5. Which enum type lets you combine members with |?

    Flag members can be combined with | and tested with in.

Summary

  • An enum is a fixed set of named constants; it replaces error-prone magic strings and numbers.
  • Members have .name and .value; look them up with Enum(value) or Enum["NAME"], and iterate over the class.
  • auto() picks values for you when they don't matter.
  • StrEnum and IntEnum members behave like strings or ints; plain Enum is stricter.
  • Enums can have methods, properties and multi-value members.
  • In match, use dotted names such as case Signal.RED:; use Flag for combinable options.

Next: OOP Principles: Encapsulation, Polymorphism and Abstraction.