Python Enum: How To Construct Enumerations in Python – KDnuggets


Picture by Writer

 

Should you’ve programmed in a language like C++ or Java, you’ve seemingly used enums to create named constants. Enums are useful when you’ve got a variable that takes considered one of a hard and fast variety of values—usually associated comparable to the times of the week, pupil grades, order standing, and the like.

Python, nevertheless, doesn’t have an express enum information kind. However you should use the enum module within the Python normal library to create enumerations. And this tutorial will train you the way. 

Let’s get began!

 

 

Enum stands for “enumeration” and consists of a set of predefined named constants. These constants are sometimes associated. Frequent examples embody months in a 12 months, days of the week, grades, order and process statuses. 

To sum up: An enum is basically a set of associated constants, the place every fixed has a significant identify related to it.

In Python, you possibly can create enums utilizing the enum module (which we’ll do shortly!).

 

Why Use Enums

 

Utilizing enums helps enhance code readability and maintainability. Here is’ how: 

  • Enums improve code readability by changing magic numbers or strings with significant labels. In addition they make the code extra self-documenting because the names of enum members convey their goal. 
  • Enums enhance code maintainability by offering a easy technique to outline and handle associated constants. 
  • By limiting variable assignments to solely legitimate enum values, enums additionally guarantee kind security. 
  • Enums facilitate straightforward iteration over and comparability of associated constants.

Now let’s create our first enumeration in Python.

 

 

We’ll create a TaskStatus enum that takes the next 4 names and values:

 

Python Enum: How To Build Enumerations in Python
Picture by Writer

 

First, we import the Enum class from the enum module to create enums. 

We then outline a brand new class TaskStatus that inherits from Enum to create an enumeration. Every member is outlined with a novel identify and an non-compulsory worth like so:

from enum import Enum
	 
class TaskStatus(Enum):
    TODO = 0
    IN_PROGRESS = 1
    DONE = 2
    ABANDONED = -1

 

All enum members we create are cases of the Enum class. It’s possible you’ll confirm it by calling the isinstance() perform as proven:

print(isinstance(TaskStatus.TODO,Enum))

 

 

Let’s print out all of the members within the TaskStatus enum by casting it into a listing:

 

It is best to see the next output:

Output >>>

[<TaskStatus.TODO: 0>, <TaskStatus.IN_PROGRESS: 1>, <TaskStatus.DONE: 2>, <TaskStatus.ABANDONED: -1>]

 

All enum members have a identify and a worth. Which means you possibly can entry enum members utilizing their names, like TaskStatus.TODO. Otherwise you entry them by worth, like TaskStatus(0).

 

 

Now that we’ve created a easy TaskStatus enum, let’s learn to carry out easy duties comparable to iterating over the enum members.

 

Iterating Over Enums

 

In Python, you possibly can work with enums just about the identical means you’re employed with any iterable. For instance, you should use the len() perform to rely the variety of enum members:

num_statuses = len(TaskStatus)
print(num_statuses)

 

 

It’s also possible to iterate over enums simply the best way you’ll over a Python iterable comparable to listing. Within the following for loop, we entry each the identify and worth of every enum member and print them out:

for standing in TaskStatus:
    print(standing.identify, standing.worth)

 

Right here’s the output:

Output >>> 

TODO 0
IN_PROGRESS 1
DONE 2
ABANDONED -1

 

Ordering in Enums

 

Within the instance, the standing and the corresponding numeric worth are as follows:

  • TODO: 0
  • IN_PROGRESS: 1
  • DONE: 2
  • ABANDONED: -1

However you can too use the default ordering by utilizing the auto() helper perform. Whenever you achieve this, you probably have ‘n’ members within the enum, the values assigned are 1 by means of n. However you possibly can cross in a begin worth, say ok, auto(ok) for the enumeration to begin at ok and go as much as ok + n.

Let’s modify the TaskStatus enum as proven:

from enum import Enum, auto

class TaskStatus(Enum):
    TODO = auto()
    IN_PROGRESS = auto()
    DONE = auto()
    ABANDONED = auto()

 

Now let’s print out the members:

 

We see that the values are 1 to 4 as anticipated:

Output >>>

[<TaskStatus.TODO: 1>, <TaskStatus.IN_PROGRESS: 2>, <TaskStatus.DONE: 3>, <TaskStatus.ABANDONED: 4>]

 

 

Now let’s construct on the TaskStatus enum that we’ve got. Create a process.py file in your working listing with the next model of the enum:

# process.py

from enum import Enum

class TaskState(Enum):
    TODO = 0
    IN_PROGRESS = 1
    DONE = 2
    ABANDONED = -1

 

Say we’ve got a process with a reputation and a present standing. And the legitimate transitions between states are as proven:

 

Python Enum: How To Build Enumerations in Python
Picture by Writer

 

Let’s create a Activity class:

class Activity:
    def __init__(self, identify, state):
        self.identify = identify
        self.state = state
    
    def update_state(self, new_state):
        # Outline legitimate state transitions based mostly on the present state
        valid_transitions = {
        	TaskState.TODO: [TaskState.IN_PROGRESS, TaskState.ABANDONED],
        	TaskState.IN_PROGRESS: [TaskState.DONE, TaskState.ABANDONED],
        	TaskState.DONE: [],
        	TaskState.ABANDONED: []
    	}
   	 
        # Test if the brand new state is a legitimate transition from the present state
        if new_state in valid_transitions[self.state]:
            self.state = new_state
        else:
            increase ValueError(f"Invalid state transition from {self.state.name} to {new_state.name}")

 

We now have an update_status() methodology that checks if the transition to the brand new state is legitimate given the present standing. For invalid transitions, a ValueError exception  is raised.

Right here’s an Occasion of the Activity class: the “Write Report” process with standing TODO:

# Create a brand new process with the preliminary state "To Do"
process = Activity("Write Report", TaskState.TODO)

# Print the duty particulars
print(f"Task Name: {task.name}")
print(f"Current State: {task.state.name}")

 

Output >>>
Activity Title: Write Report
Present State: TODO

 

Updating the standing of the duty to IN_PROGRESS ought to work because it’s a legitimate state transition:

# Replace the duty state to "In Progress"
process.update_state(TaskState.IN_PROGRESS)
print(f"Updated State: {task.state.name}")

 

Output >>> Up to date State: IN_PROGRESS

 

And as soon as the duty is full, we will replace its standing to DONE:

# Replace the duty state to "DONE"
process.update_state(TaskState.DONE)
print(f"Updated State: {task.state.name}")

 

Output >>> Up to date State: DONE

 

However if you happen to attempt to replace the standing to an invalid one, comparable to attempting to replace DONE to TODO, you’ll run into ValueError exception:

# Try to replace the duty state to an invalid state
process.update_state(TaskState.TODO)

 

Right here’s the traceback of the ValueError raised due to invalid state transition from DONE to TODO:

Traceback (most up-to-date name final):
  File "/home/balapriya/enums/task.py", line 46, in 
	process.update_state(TaskState.TODO)
  File "/home/balapriya/enums/task.py", line 30, in update_state
	increase ValueError(f"Invalid state transition from {self.state.name} to {new_state.name}")
ValueError: Invalid state transition from DONE to TODO

 

 

On this tutorial, we realized the way to construct enumerations in Python by coding a easy TaskStatus enum. We realized the way to entry enum members and iterate over them. 

Additionally, we realized how default ordering works if you happen to select to make use of the auto() helper perform to set the values for enum members. We then tried utilizing the TaskStatus enum in a extra useful instance. 

You could find the code examples on GitHub. I’ll see you all quickly in one other Python tutorial. Till then, joyful coding!
 
 

Bala Priya C is a developer and technical author from India. She likes working on the intersection of math, programming, information science, and content material creation. Her areas of curiosity and experience embody DevOps, information science, and pure language processing. She enjoys studying, writing, coding, and occasional! At present, she’s engaged on studying and sharing her data with the developer group by authoring tutorials, how-to guides, opinion items, and extra. Bala additionally creates participating useful resource overviews and coding tutorials.

Recent articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here