Using Enumerations: Two Practical Examples
With an enumeration, you can group these numeric constants and assign them readable and descriptive names that you can use and reuse in your code later. Let’s say you have the
process_response() function seen on screen that retrieves and processes HTTP content directly from the web.
01:07 In this example, if a match occurs, then the code block in the matched case runs. If no match occurs, then the default case runs. Note that the default case is the one that uses an underscore as a match criterion.
finally clause closes the active connection to avoid resource leaks. Even though this code works, it can be challenging to read and understand for people who are unfamiliar with HTTP status codes and their corresponding meanings.
process_response(), you use human-readable and descriptive names that provide context and content information. Now, anyone reading the code will immediately know the match criteria are HTTP status codes, and they’ll also spot the meaning of each target code quickly.
03:39 Another interesting use case of enumerations is using them to re-create the different possible states of a given system. If your system can be in exactly one of a finite number of states at any given time, then your system works as a state machine.
Enumerations are useful when you need to implement this common design pattern. As an example of how to use an enum to implement the state machine pattern, you create a minimal disk player simulator. To start, go ahead and create
disk_player.py with the content seen on screen.
Here you define the
State class. This class groups all the possible states of your disk player: empty, stopped, paused, and playing. You can now code the
DiskPlayer player class, which would look similar to the code seen on screen.
To complete your example, you’ll use the traditional
if __name__ ==
"__main__" idiom. To wrap up a few lines of code that will allow you to try out the
DiskPlayer class, here you first define an
actions variable, which holds the sequence of methods that you’ll call from
DiskPlayer in order to try out the class.
06:48 Of course, this example is minimal and doesn’t consider all the potential scenarios. It’s a demonstrative example of how you could use an enumeration to implement the state machine pattern in your code.
Become a Member to join the conversation.