- Aliases
- and operator
- Booleans
- Classes
- Code blocks
- Comments
- Conditional statements
- Console
- Data structures
- datetime module
- Decorator
- Dictionaries
- Docstrings
- enum
- enumerate() function
- Equality operator
- Exception handling
- False
- File handling
- Floats
- For loops
- Formatted strings
- Functions
- Generator
- Greater than operator
- Greater than or equal to operator
- If statement
- in operator
- Indices
- Inequality operator
- Integers
- Iterator
- Lambda function
- Less than operator
- Less than or equal to operator
- List append() method
- List comprehension
- List insert() method
- List pop() method
- List sort() method
- Lists
- Logging
- map() function
- Match statement
- Math module
- Modules
- Multiprocessing
- Multithreading
- None
- not operator
- OOP
- or operator
- Parameters
- print() function
- Random module
- range() function
- Recursion
- Regular expressions
- requests Library
- return statement
- round() function
- Sets
- SQLite
- String join() method
- String replace() method
- String split() method
- Strings
- time.sleep() function
- True
- try...except statement
- Tuples
- Variables
- While loops
- Zip function
PYTHON
Python Enum: Creating Enumerations in Python
Enums in Python define symbolic names for groups of related constants.
How to Use Enums in Python
Enums can help define constant values that remain unchanged throughout the execution of the program.
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
Enums often work with constant values to ensure consistency across the codebase.
Basic Usage
today = Day.MONDAY
print(today)
Enum Syntax in Python
Enums in Python follow a clear and consistent syntax. Each member is defined as a class attribute, and its value is assigned immediately. The definition order of the members is preserved, which allows developers to iterate over them in the same sequence they were declared.
from enum import Enum
class Status(Enum):
NEW = 1
IN_PROGRESS = 2
DONE = 3
The syntax makes enums easy to read and understand, while the definition order is particularly useful for ordered lists or displays in user interfaces.
When to Use Enum in Python
Enums are widely used in programming, with many use cases ranging from managing application states to defining groups of constants.
They can be useful whenever you’re working with groups of related constants. For example, you might use enums to manage constant values or define use cases where specific attributes must remain consistent.
Enums also allow seamless integration with Python’s standard library, making them highly versatile.
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.")
Enums can also work seamlessly with boolean expressions to validate comparisons.
Examples of Using Python Enum
Web Application Settings
One of the most common use cases for enums is managing configuration settings in web applications, like toggling between debug and production modes.
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'
Enums in API Development
Enums play a significant role in API development by defining consistent constant values for request parameters, response codes, and configuration settings. This ensures that APIs are less prone to errors and easier to maintain.
class Status(Enum):
SUCCESS = "success"
FAILURE = "failure"
def api_response(status: Status):
return {"status": status.value}
response = api_response(Status.SUCCESS)
print(response) # Outputs: {'status': 'success'}
Using enums in API development helps enforce validation and guarantees that only predefined constant values are passed between the client and server.
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 member names and member values.
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>}
Member names refer to symbolic identifiers like ELECTRONICS, while member values represent their assigned values, such as 1.
The __members__
attribute allows you to access all enumeration members of an enum. These members include both the names and their associated values.
print(Status.__members__)
# Outputs: {'SUCCESS': <Status.SUCCESS: 'Success'>, 'FAILURE': <Status.FAILURE: 'Failure'>}
This attribute is useful for dynamically inspecting an enum's enumeration members.
Using StrEnum for String-based Enums
Python's StrEnum
is a specialized version of enums where all members are strings. It ensures compatibility with string operations while retaining all the benefits of enums.
from enum import StrEnum
class Color(StrEnum):
RED = "red"
GREEN = "green"
BLUE = "blue"
print(Color.RED) # Outputs: 'Color.RED'
print(Color.RED.value) # Outputs: 'red'
StrEnum
is particularly useful when enums need to interact with string-based data, such as JSON or text-based APIs.
Working with String Representation in Enums
Enums provide two methods for representing their members as strings: str()
and repr()
. These methods are particularly useful for debugging or displaying enum members in a readable format.
str()
: Provides a user-friendly name for the enum member.repr()
: Offers a more detailed representation, including the enum class and member.
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(str(Color.RED)) # Outputs: 'Color.RED'
print(repr(Color.RED)) # Outputs: '<Color.RED: 1>'
By combining str()
and repr()
, you can implement custom outputs for enums, making them more accessible in logs or user-facing applications.
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
To ensure all enumeration members have unique values, use the @unique
decorator. This enforces that no two members share the same value.
from enum import Enum, unique
@unique
class UniqueColor(Enum):
RED = 1
BLUE = 2
GREEN = 3
By enforcing unique values, you reduce the risk of logical errors in your application.
Auto-generating Values
You can use the auto()
function to automatically assign increasing [integer[(https://mimo.org/glossary/python/integer) values to enum members, which is helpful when you want to define enum types with sequential numbering. These enumeration numbers make code cleaner and easier to maintain.
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
Python enums allow for boolean logic when combining or comparing members. Additionally, enums provide methods for accessing member names and member values, making them versatile in dynamic scenarios.
class Permission(Enum):
READ = 1
WRITE = 2
print(Permission.READ.name) # Outputs: 'READ'
print(Permission.READ.value) # Outputs: 1
# Using boolean logic to check permissions
if Permission.WRITE in [Permission.READ, Permission.WRITE]:
print("Permission granted.")
By leveraging boolean operations and methods like name
and value
, you can build powerful and flexible enums for your applications.
For more advanced usage, you can use IntEnum
, Flag
, and IntFlag
to perform additional operations like bitwise operations.
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.")
This flexibility makes enums powerful for advanced use cases where control over constant values is critical.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.