Tags: Python, Enum, Constants, Values, Readability, Maintainability
Python enums are a great way to improve the readability and maintainability of your code. Enums provide readable names that are bound to constant values, making it easier to understand and work with different states or options in your program.
To begin using enums in Python, you need to import the Enum
class from the enum
standard library module. Here’s an example:
from enum import Enum
Once imported, you can define your own enum class by subclassing Enum
and assigning meaningful names to the constant values. For example:
class State(Enum):
INACTIVE = 0
ACTIVE = 1
With this enum class defined, you can now refer to the different states using the names you’ve assigned. For instance, State.INACTIVE
and State.ACTIVE
act as constants in your code.
When printing an enum value, such as State.ACTIVE
, instead of returning the underlying constant value (e.g., 1
), it will display the enum name itself (State.ACTIVE
). If you still need to access the underlying value, you can use State.ACTIVE.value
.
You can also retrieve an enum value using the assigned constant value or the name itself. For example, State(1)
or State['ACTIVE']
will both return State.ACTIVE
.
To get a list of all possible values of an enum, you can use the list()
function on the enum class:
list(State) # Returns: [<State.INACTIVE: 0>, <State.ACTIVE: 1>]
If you want to count the number of values in an enum, you can simply use the len()
function:
len(State) # Returns: 2
By using enums in your Python code, you can enhance the readability and maintainability of your programs, making it easier for yourself and others to understand and work with different states or options in your codebase.