Python Tutorial
Python Variable
Python Operators
Python Sequence
Python String
Python Flow Control
Python Functions
Python Class and Object
Python Class Members (properties and methods)
Python Exception Handling
Python Modules
Python File Operations (I/O)
An enumeration, or Enum, is a symbolic name for a set of values. Enumerations are often used to define a group of named constants that represent distinct elements of a collection. In Python, the enum
module provides a way to create enumerations.
In this tutorial, we'll demonstrate how to create and use Enums in Python.
Example: Creating an Enum
Let's create an Enum called Day
that represents the days of the week:
from enum import Enum class Day(Enum): MONDAY = 1 TUESDAY = 2 WEDNESDAY = 3 THURSDAY = 4 FRIDAY = 5 SATURDAY = 6 SUNDAY = 7
In this example, we import the Enum
class from the enum
module and create a subclass called Day
. The Day
Enum has named constants for each day of the week, with integer values from 1 to 7.
Example: Using the Enum
Now that we've created the Day
Enum, let's see how to use it:
# Access an Enum member by name print(Day.MONDAY) # Output: Day.MONDAY print(Day.MONDAY.name) # Output: MONDAY print(Day.MONDAY.value) # Output: 1 # Iterate over the Enum members for day in Day: print(day) # Output: Day.MONDAY, Day.TUESDAY, ..., Day.SUNDAY # Get an Enum member by value print(Day(3)) # Output: Day.WEDNESDAY print(Day(3).name) # Output: WEDNESDAY # Compare Enum members print(Day.MONDAY == Day.MONDAY) # Output: True print(Day.MONDAY == Day.TUESDAY) # Output: False
In this example, we demonstrate various ways to use the Day
Enum:
In conclusion, Enums in Python provide a convenient way to define named constants that represent distinct elements of a collection. Enums improve code readability and reduce the risk of errors by allowing you to use symbolic names instead of hardcoded values.
Creating Enums in Python:
enum
module, which provides a way to create named constant values. Enums can be defined using the Enum
class.from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3
Defining members in a Python Enum:
from enum import Enum class Direction(Enum): NORTH = "north" SOUTH = "south" EAST = "east" WEST = "west"
Accessing Enum values in Python:
value
attribute.direction = Direction.NORTH print(direction) # Output: Direction.NORTH print(direction.value) # Output: north
Iterating over Enum values in Python:
for direction in Direction: print(direction)
Enum members with custom values in Python:
from enum import Enum class Status(Enum): ACTIVE = "active" INACTIVE = "inactive"
Enum comparisons and identity in Python:
status1 = Status.ACTIVE status2 = Status.ACTIVE print(status1 == status2) # Output: True print(status1 is status2) # Output: True