enum

Enumerations: a set of named constants, e.g. difficulty levels or task statuses, instead of loose strings and numbers.

On this page

Example

#
Python
from enum import Enum

class Difficulty(Enum):
    EASY = 1
    MEDIUM = 2
    HARD = 3

level = Difficulty.HARD
print(level)
print(level.name, level.value)
print(level is Difficulty.HARD)
print(Difficulty(2).name, Difficulty["EASY"].value)
print([d.name for d in Difficulty])
Resultsaved result, you can check it
Difficulty.HARD
HARD 3
True
MEDIUM 1
['EASY', 'MEDIUM', 'HARD']

Definition and usage

#

The enum module lets you define an enumeration, that is a class with a closed list of named values. Instead of typing the strings "easy" and "hard" in your code, where a typo is easy to make, you create a Difficulty(Enum) class with the members EASY, MEDIUM, and HARD. Each member has a name (.name) and a value (.value).

Members are compared with is or ==, and a typo in a name, e.g. Difficulty.EASSY, immediately raises AttributeError. You can iterate over an enumeration in definition order, and look up a member by value (Difficulty(2)) or by name (Difficulty["HARD"]). Values do not have to be numbers, and the auto() function assigns them automatically.

An ordinary Enum member is not equal to its value: Difficulty.EASY == 1 is False. When members should behave like strings or numbers, e.g. when saving to JSON or comparing with data from a database, use StrEnum or IntEnum. Enumerations work well with the match statement, where the member is given with a dot: case Difficulty.HARD:.

Syntax

#
Syntax
from enum import Enum, auto

class Name(Enum):
    MEMBER = value
    OTHER = auto()

Name.MEMBER.name
Name.MEMBER.value
Name(value)
Name["MEMBER"]

The most important elements

#
  • Enum

    The basic enumeration. Members are equal only to themselves, not to their values.
  • StrEnum

    Members are strings: they equal their values and go into f-strings as just the value. Since Python 3.11.
  • IntEnum

    Members are integers, so they can be compared with numbers and used in calculations.
  • Flag

    Values can be combined with the | operator and checked with in, e.g. a set of permissions.
  • auto()

    Assigns values automatically: in Enum successive numbers starting from 1, and in StrEnum the member name in lowercase.

More examples

#
StrEnum and auto()
Python
from enum import StrEnum, auto

class Status(StrEnum):
    TODO = auto()
    IN_PROGRESS = auto()
    DONE = auto()

task = {"number": "7_3", "status": Status.DONE}

print(Status.IN_PROGRESS.value)
print(task["status"] == "done")
print(f"Status: {task['status']}")
print(Status("todo").name)
Resultsaved result, you can check it
in_progress
True
Status: done
TODO
Enumeration methods and match
Python
from enum import Enum

class Difficulty(Enum):
    EASY = 1
    MEDIUM = 2
    HARD = 3

    @property
    def exp(self):
        return self.value * 10

def label(difficulty):
    match difficulty:
        case Difficulty.EASY:
            return "A warm-up"
        case Difficulty.HARD:
            return "For the persistent"
        case _:
            return "Standard"

for d in Difficulty:
    print(d.name, d.exp, label(d))
print(Difficulty.EASY == 1)
Resultsaved result, you can check it
EASY 10 A warm-up
MEDIUM 20 Standard
HARD 30 For the persistent
False
Flag: combining permissions
Python
from enum import Flag, auto

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

mentor = Permission.READ | Permission.WRITE
print(Permission.WRITE in mentor, Permission.DELETE in mentor)
print([p.name for p in mentor])
print(mentor.value)
Resultsaved result, you can check it
True False
['READ', 'WRITE']
3

Good practices

#
  • Compare members with other members, not with strings or numbers. For comparisons with raw values, there are StrEnum and IntEnum.
  • Write member names in capital letters, like constants: Status.DONE.
  • For saving to JSON, use .value, and when reading, convert the value back to a member with Status(value).

Related entries

#

Practise it in lessons

#

Spotted a mistake or missing an example? Write to us.