enum
Enum
(short for enumeration) is a class in Python used to define a set of named, immutable constants. Enumerations improve code readability and maintainability by replacing magic numbers or strings with meaningful names. Enums are part of Python’s built-in enum
module, introduced in Python 3.4.
Note: Magic numbers are unclear, hardcoded values in code. For example,
80
in a speed-checking program might be confusing. Replacing it with an enum constant, likeSpeedLimit.HIGHWAY
, makes the code easier to read and maintain.
Syntax
from enum import Enum
class EnumName(Enum):
MEMBER1 = value1
MEMBER2 = value2
EnumName
: The name of the enum class.MEMBER1
,MEMBER2
: Names of the constants.value1
,value2
: Values assigned to the constants (e.g. numbers or strings).
enum
Module
The enum
module provides the Enum
class for creating enumerations. It also includes:
IntEnum
: Ensures that the values of the enuemration are integers.Flag
: Allows combining constants with bitwise operations.Auto
: Automatically assigns values to the enumeration members.
Enums also provide methods like:
.name
: Returns the name of the enum member (as a string)..value
: Returns the value assigned to the enum member.
Example
This example demonstrates how to create an enum for days of the week with integer values:
from enum import Enumclass Weekday(Enum):MONDAY = 1TUESDAY = 2WEDNESDAY = 3# Accessing membersprint(Weekday.MONDAY)print(Weekday.MONDAY.name)print(Weekday.MONDAY.value)# Iterating through membersfor day in Weekday:print(day)
This example results in the following output:
Weekday.MONDAYMONDAY1Weekday.MONDAYWeekday.TUESDAYWeekday.WEDNESDAY
Codebyte
This example demonstrates how enums can represent traffic light states and associate actions with each state:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours