- Alias
- and operator
- append()
- Booleans
- Classes
- Code block
- Comments
- Conditions
- Console
- datetime module
- Dictionaries
- enum
- enumerate() function
- Equality operator
- False
- Float
- For loop
- Formatted strings
- Functions
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Index
- Indices
- Inequality operator
- insert()
- Integer
- Less than operator
- Less than or equal to operator
- List sort() method
- Lists
- map() function
- Match statement
- Modules
- None
- or operator
- Parameter
- pop()
- print() function
- range() function
- Regular expressions
- requests Library
- Return
- round() function
- Sets
- String
- String join() method
- String replace() method
- String split() method
- The not operator
- time.sleep() function
- True
- try...except statement
- Tuples
- Variables
- While loop
PYTHON
Python Enum: Creating Enumerations in Python
Enums in Python define symbolic names for groups of related constants.
How to Use Enums in Python
You can define an enum by creating a subclass of Enum
with class attributes. Since the Enum
class belongs to the enum
module, you need to import the module at the top of your Python script.
from enum import Enum
class Day(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
SUNDAY = 7
Basic Usage
today = Day.MONDAY
print(today)
When to Use Enum in Python
Enums can be useful whenever you’re working with groups of related constants.
Defining Constant Groups
You can use enums to represent groups of related constants, such as days of the week or severity levels.
class SeverityLevel(Enum):
LOW = 1
MEDIUM = 2
HIGH = 3
CRITICAL = 4
Improving Code Readability
Enums also improve code readability by using meaningful names instead of arbitrary values. This makes your code easier to understand and maintain, as the purpose of each value is clear.
def alert(level):
if level == SeverityLevel.HIGH:
print("Take immediate action!")
alert(SeverityLevel.HIGH) # Outputs: 'Take immediate action!'
Type-Safe Comparisons
Enums ensure you use only valid constants, preventing errors caused by invalid values. Maintaining type safety makes your code more robust and less prone to bugs.
class Status(Enum):
SUCCESS = "Success"
FAILURE = "Failure"
status = Status.SUCCESS
if status == Status.SUCCESS:
print("Operation was successful.")
Examples of Using Python Enum
Web Application Settings
A web application might use enums to define configuration settings. This makes it easier to manage different modes or configurations.
class Config(Enum):
DEBUG = True
PRODUCTION = False
# Example usage in a web app configuration
current_config = Config.PRODUCTION
if current_config == Config.DEBUG:
print("Debug mode is enabled")
else:
print("Production mode is enabled")
Workflow State Management
Workflow management systems can use enums to represent different states of a task. This makes it easier to manage and transition between different states in a controlled manner.
class TaskState(Enum):
TO_DO = 1
IN_PROGRESS = 2
COMPLETED = 3
current_state = TaskState.TO_DO
print(current_state) # Outputs: 'TaskState.TO_DO'
# Transitioning task state
if current_state == TaskState.TO_DO:
current_state = TaskState.IN_PROGRESS
print("Task is now in progress")
E-commerce Product Categories
An e-commerce application might use enums to map numeric values to meaningful names for product categories. This makes it easier to manage and display product information in a user-friendly way.
class ProductCategory(Enum):
ELECTRONICS = 1
CLOTHING = 2
HOME = 3
# Example usage in product listing
product = {'name': 'Laptop', 'category': ProductCategory.ELECTRONICS}
print(f"Product: {product['name']}, Category: {product['category'].name}") # Outputs: 'Product: Laptop, Category: ELECTRONICS'
Calendar Application
A calendar application might use enums to represent the days of the week, improving readability and reducing errors. This approach helps ensure that day-related operations are handled consistently and correctly.
class Weekday(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
SUNDAY = 7
# Scheduling an event
event_day = Weekday.FRIDAY
print(f"The event is scheduled for {event_day.name}") # Outputs: 'The event is scheduled for FRIDAY'
Learn More About Python Enum
Python Enum Class Methods
The Enum
class provides several built-in methods like name
, value
, and __members__
to access enum properties. These methods make it easy to work with enums and retrieve their values and names.
print(ProductCategory.ELECTRONICS.name) # Outputs: 'ELECTRONICS'
print(ProductCategory.ELECTRONICS.value) # Outputs: 1
print(ProductCategory.__members__) # Outputs: {'ELECTRONICS': <ProductCategory.ELECTRONICS: 1>, 'CLOTHING': <ProductCategory.CLOTHING: 2>, 'HOME': <ProductCategory.HOME: 3>}
Iterating Over Enums
You can iterate over the members of an enum using a for loop. This capability is useful for performing operations on all enum values or for generating lists of names or values.
for day in Weekday:
print(day)
# Outputs: 'Weekday.MONDAY', 'Weekday.TUESDAY', ...
Comparing Enum Members
You can compare enum members using logical operators. This allows you to perform operations based on the order or equality of enum values.
if Weekday.MONDAY < Weekday.FRIDAY:
print("Monday comes before Friday.")
Customizing Enum Members
Using the property
decorator, you can create enums with more complex data types and custom methods. This allows you to encapsulate additional logic and data within your enums.
class Planet(Enum):
MERCURY = (0.39, 3.30e23)
VENUS = (0.72, 4.87e24)
EARTH = (1.00, 5.97e24)
def __init__(self, distance_from_sun, mass):
self.distance_from_sun = distance_from_sun
self.mass = mass
@property
def density(self):
return self.mass / (4/3 * 3.14159 * (self.distance_from_sun ** 3))
print(Planet.EARTH.density) # Outputs Earth's density
Auto-generating Values
You can use the auto()
function to automatically assign increasing integer values to enum members. This simplifies the process of defining enums with sequential values.
from enum import auto
class ErrorCode(Enum):
NOT_FOUND = auto()
UNAUTHORIZED = auto()
FORBIDDEN = auto()
print(list(ErrorCode)) # Outputs: [<ErrorCode.NOT_FOUND: 1>, <ErrorCode.UNAUTHORIZED: 2>, <ErrorCode.FORBIDDEN: 3>]
Advanced Enum Techniques
For more advanced usage, you can use IntEnum
, Flag
, and IntFlag
to perform additional operations like bitwise operations. These specialized enums provide additional functionality and are useful in various contexts.
from enum import IntFlag
class Permission(IntFlag):
READ = 1
WRITE = 2
EXECUTE = 4
# Assign multiple permissions
permissions = Permission.READ | Permission.WRITE
if permissions & Permission.READ:
print("Read permission granted.")
if permissions & Permission.EXECUTE == 0:
print("Execute permission denied.")
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.