enum
Enumerations: a set of named constants, e.g. difficulty levels or task statuses, instead of loose strings and numbers.
Example
#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])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
#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 within, e.g. a set of permissions.auto()
Assigns values automatically: inEnumsuccessive numbers starting from 1, and inStrEnumthe member name in lowercase.
More examples
#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)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)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)Good practices
#- Compare members with other members, not with strings or numbers. For comparisons with raw values, there are
StrEnumandIntEnum. - 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 withStatus(value).
Related entries
#- classDefines a class: a template for objects that combines data with the functions that act on it.
- match, casePattern matching: choosing a branch of code based on a valueโs data and shape.
- @dataclassA decorator that generates __init__, __repr__, and __eq__ for a data-storing class, based on type-annotated fields.
- typingType annotations: a description of what values a function expects and what it returns. Checked by editors and tools such as mypy.
- jsonConverts Python data to JSON text and back. The basis for saving data and communicating with APIs.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.