Coding

Enum in Python: Examples and When to Use Them

An enum in Python is a class that defines a fixed set of named constants. Subclass enum.Enum, list the members as class attributes, and use them as Color.RED instead of loose numbers or strings.

The module is in the standard library, so there is nothing to install. All examples below use the documented behavior of the enum module; output lines are example output from the Python documentation.

How to define an enum in Python

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

Each line inside the class creates a member. A member has two attributes: name, the identifier you wrote, and value, whatever you assigned to it.

>>> Color.RED
<Color.RED: 1>
>>> print(Color.RED)
Color.RED
>>> Color.BLUE.name
'BLUE'
>>> Color.RED.value
1

The repr() of a member shows the class, the name and the value. The str() shows only the class and the name, which is what print() uses. Because the class is a normal Python class, it follows the same rules as any other; see Python classes explained if you want the background on how class attributes work.

There is also a functional form that builds the same class in one call:

Color = Enum('Color', [('RED', 1), ('GREEN', 2), ('BLUE', 3)])

The class syntax is easier to read and is what most code uses.

Look up members by name or by value

You will often receive a string or a number from a file, a form or an API and need the matching member. Two lookups cover this:

>>> Color(1)
<Color.RED: 1>
>>> Color['RED']
<Color.RED: 1>

Calling the class with a value (Color(1)) looks a member up by value. Indexing the class with a name (Color['RED']) looks it up by name. A name that does not exist raises KeyError, and a value that does not exist raises ValueError. That behavior is useful: bad input fails at the boundary instead of travelling through your program as a plain number. Wrap the lookup in try and except ValueError when the input is not trusted (see Python try and except).

Because the lookup is by name or value, an enum can replace a dictionary that maps strings to numbers. If you only need a quick mapping with no extra behavior, though, a dictionary is still the simpler tool.

Loop over an enum

An enum class is iterable. Members come out in the order you defined them.

>>> list(Color)
[<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>]
>>> len(Color)
3
>>> Color.RED in Color
True
>>> list(reversed(Color))
[<Color.BLUE: 3>, <Color.GREEN: 2>, <Color.RED: 1>]

This makes it easy to build a menu, validate that a value is allowed, or generate documentation from the members themselves, with no second list to keep in sync.

Compare enum members

Members of a plain Enum are compared by identity. A member equals itself and nothing else, not even the number it holds:

>>> Color.BLUE == 2
False
>>> Color.RED < Color.BLUE
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'Color' and 'Color'

Use == or is to test which member you have. Ordering with < is not supported on a plain Enum. If your members have a natural order, such as severity levels, use IntEnum (below) or compare the .value attributes yourself.

Aliases and the @unique decorator

Duplicate member names are an error. Duplicate values are allowed, and the second name becomes an alias of the first:

>>> class Shape(Enum):
...     SQUARE = 2
...     DIAMOND = 1
...     CIRCLE = 3
...     ALIAS_FOR_SQUARE = 2
...
>>> Shape.ALIAS_FOR_SQUARE
<Shape.SQUARE: 2>
>>> list(Shape)
[<Shape.SQUARE: 2>, <Shape.DIAMOND: 1>, <Shape.CIRCLE: 3>]

Iteration skips aliases, but the class attribute __members__ includes them. An accidental duplicate value is a common typo, since it is silent. The @unique decorator turns it into an error:

>>> from enum import Enum, unique
>>> @unique
... class Mistake(Enum):
...     ONE = 1
...     TWO = 2
...     THREE = 3
...     FOUR = 3
...
Traceback (most recent call last):
...
ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE

Use @unique whenever aliases would be a mistake in your design.

Use auto() so you do not number members by hand

When the actual values do not matter, let Python assign them:

from enum import Enum, auto

class Size(Enum):
    SMALL = auto()
    MEDIUM = auto()
    LARGE = auto()

For Enum and IntEnum, auto() starts at 1 and adds one each time, so the values here are 1, 2 and 3. For Flag and IntFlag it gives the next power of two, and for StrEnum it gives the lower-cased member name. auto() has existed since Python 3.6. You can change what it produces by defining _generate_next_value_; the Python documentation shows a version that returns the member name, so NORTH = auto() has the value 'NORTH'.

IntEnum: members that are also integers

An IntEnum member is a real int, so it compares with numbers and with other integer enums:

from enum import IntEnum

class Number(IntEnum):
    ONE = 1
    TWO = 2
    THREE = 3
>>> Number.THREE == 3
True
>>> Number.ONE + Number.TWO
3

The sum is a plain int, not an enum member. That convenience is also the weakness. The documentation shows that two unrelated IntEnum classes compare equal when their values match (Shape.CIRCLE == Request.POST is True when both are 1), which is the kind of mix-up an enum is supposed to prevent. Choose IntEnum when you must interoperate with code that expects integers, such as a numeric protocol or a library API. Otherwise prefer plain Enum.

StrEnum: members that are also strings

Added in Python 3.11, StrEnum members are strings, which suits values that end up in JSON, URLs or log lines.

from enum import StrEnum

class Status(StrEnum):
    OK = 'ok'
    FAILED = 'failed'
>>> Status.OK == 'ok'
True
>>> str(Status.OK)
'ok'

Here str() returns the value, not Status.OK, which is different from a plain Enum. The documentation also warns that some standard-library code checks type(x) == str exactly; in that case pass str(Status.OK).

Flag: combine options with | and &

Flag is for options that can be switched on together, like file permissions. Members are usually powers of two, and auto() picks them for you.

from enum import Flag, auto

class Perm(Flag):
    R = auto()
    W = auto()
    X = auto()
>>> rw = Perm.R | Perm.W
>>> rw
<Perm.R|W: 3>
>>> Perm.R in rw
True
>>> list(rw)
[<Perm.R: 1>, <Perm.W: 2>]
>>> bool(Perm(0))
False

Use | to combine, in to test, and & to intersect. A combination with no common flags is falsy. IntFlag works the same way but its members are also integers, so Color.RED | 2 is allowed.

When to use an enum

An enum is a good fit when a value must be one of a small, known set, and the code branches on it: order states (PENDING, SHIPPED), log levels, directions, file modes, response types. Compared with bare strings or numbers, you get:

  • One place to define the set. Adding a member changes one class, and iteration picks it up.
  • Failure on bad input. Color(99) raises ValueError instead of letting a bad number through.
  • Readable output. A log line that shows Status.FAILED says more than 3.
  • No accidental equality. With a plain Enum, a status can never be confused with a color that happens to hold the same number.

Skip the enum when the set is open-ended or changes at runtime, such as user-created categories. A dictionary or a database table is the better model there. Also skip it for a single constant; a module-level name is enough.

Python versions to know

FeatureAdded in Python
enum module, Enum, IntEnum, @unique3.4
Flag, IntFlag, auto()3.6
StrEnum, @verify, ReprEnum3.11

If you must support a version older than 3.11, you will have to write class Name(str, Enum) in place of StrEnum, and check the output of str() on your target version, since it differs.

If it still fails

A ValueError when calling Color(x) means x is not one of the values. Print list(Color) to see the allowed ones, and check that you are not passing the name where the value is expected (use Color['RED'] for names). A TypeError about '<' means you are ordering members of a plain Enum; compare .value or switch to IntEnum. An ImportError on StrEnum means the interpreter is older than 3.11.

Frequently asked questions

What is an enum in Python?
An enum is a class, built by subclassing enum.Enum, that defines a fixed set of named constants called members. Each member has a name and a value, and the members are unique objects you can compare, iterate over and look up by name or by value.
Is enum built into Python?
It is part of the standard library, not a keyword. The enum module has been available since Python 3.4, so you import it with from enum import Enum. You do not need to install anything.
What is the difference between Enum and IntEnum?
Members of a plain Enum never compare equal to integers, so Color.BLUE == 2 is False. Members of an IntEnum are also integers, so Number.THREE == 3 is True and they can be used where an int is expected. The cost is that an IntEnum can be mixed up with unrelated integers or with another IntEnum that has the same value.
Which Python version added StrEnum?
StrEnum was added in Python 3.11. On older versions, define class Name(str, Enum) to get members that are also strings, but note that str() of such a member behaves differently from StrEnum.
Can I add or change enum members at runtime?
Members are meant to be constants, and the class is not designed to be edited after it is created. If you need a set that changes, use a dictionary or a set instead of an enum.

Sources