<img alt="enums in Python" data- data-src="https://kirelos.com/wp-content/uploads/2023/08/echo/enums-in-Python.jpg/w=800" data- decoding="async" height="420" src="data:image/svg xml,” width=”800″>

Enums are a popular data type in programming languages such as C, C , and Java. They help you write type-safe and more readable code.

In Python, enums were not always supported. However, since version 3.4, Python now supports enums. This article is a guide on how to create enums, how to use them, and how they improve code readability.

What Are Enums, and What Do They Do?

An enum or enumeration is a data type defined by the set of values it can take. This set of values is referred to as its set of members. Enums enable you to define the values that a variable could have more narrowly. This helps you write type-safe code. It also improves readability.

Some Terms to Know

As we discuss enums, there are terms that I should define first, as we will be using them a lot. These are members and values.

  • Members: These are the named constants that form the set of values that belong to the enum. For example, the Days enum could contain the following members: Sunday, Monday, Tuesday, etc.
  • Values: These are the values used internally to represent each enum member distinctly. This will make it possible to do comparisons. For example, in the Days enum, Sunday could have a value of 0, Monday a value of 1, Tuesday a value of 2, etc.

Now, we will discuss how Enums improve your code.

How Enums Improve Your Code

Enums improve your code and make it more readable and less error-prone. Below are some of the reasons why you should use them:

  • Enums enable you to define what values a variable or function argument expects clearly. Making your intentions with a variable or function argument clear enables people to understand your code with ease.
  • Enums also make your code self-documenting. This means you do not have to add comments or documents to specify what values a function expects. Rather, your enum specifies what values are expected.
  • This also enables IDEs to highlight errors when you pass incorrect values and provide autocompletion support.
  • As a result, your code becomes typesafe and less likely to produce runtime errors.

Next, we will discuss how to create Enums in Python.

How to Create Enums in Python

Python does not have native support for enums. But it does provide an enums module in the standard library. We will use that module in this tutorial. There are also two methods for creating enums in Python: Classes or the Function API. I will cover both in this section.

Prerequisites

To follow this tutorial, you will need Python 3.4 installed. This version of Python comes with the enum module in the standard library. If you haven’t done that, here’s a tutorial to help you:

<img alt="YouTube video" data-pin-nopin="true" data-src="https://kirelos.com/wp-content/uploads/2023/08/echo/maxresdefault.jpg64f07ed40a441.jpg" height="720" nopin="nopin" src="data:image/svg xml,” width=”1280″>

To follow the tutorial, you will need to know some Python. This includes basic Python and more advanced object-oriented programming concepts like classes and inheritance.

#1. The Class Method

The first method for creating enums is using classes. You first import the enum class from the enum module. Next, you create your enum by creating a class. This class will inherit from the Enum class you imported earlier.

from enum import Enum

class Direction(Enum):
    NORTH = 0
    EAST = 1
    SOUTH = 2
    WEST = 3

You can also assign any values you want to the members of an enum. Here’s an example: instead of assigning 0, 1, 2, and 3 to our directions enum, we assign their corresponding heading values of 0, 90, 180, and 270.

from enum import Enum

class Direction(Enum):
    NORTH = 0
    EAST = 90
    SOUTH = 180
    WEST = 270

Alternatively, using the range function is a more concise way of generating the above. The code snippet below demonstrates how:

from enum import Enum

class Direction(Enum):
    NORTH, EAST, SOUTH, WEST = range(0, 360, 90)

In this case, we generate values using the range function. We specify 0 as our start value, 360 as our end value, and 90 as the incrementing value. We destructure the values from the iterable, similar to how we destructure tuples. If you want to read more about tuple destructuring, here’s an article on tuples in Python.

Enum classes are abstract classes. This means they are not meant to be instantiated. Instead, their properties, representing the enum members in this case, are accessed directly.

#2. The Function Method

The function method is an alternative to the subclassing method.

from enum import Enum

Direction = Enum("Direction", ["NORTH", "EAST", "SOUTH", "WEST"])

In the above code snippet, we created an enum called Direction. It is accessible using four members, which we provided as a second argument. By default, these members are given values from 1. So North is 1, East is 2, and so on. This is the case and not a zero-based index like expected because 0 is false. So, to make all values true, the values are numbered from 1.

Alternatively, you can assign values to your members by passing in the members as a list of tuples. Each tuple comprises two elements: the name of the member and the value of that member.

from enum import Enum

Direction = Enum(
    name = "Direction",
    values = [
        ("NORTH", "n"),
        ("EAST", "e"),
        ("SOUTH", "s"),
        ("WEST", "w"),
    ]
)

You’ll also notice that I used strings instead of integers when assigning values to the members in the above example. This demonstrates that strings are as valid as integers when assigning values.

How to Use Enums

In the previous section, we covered creating enums and assigning values to the members. This section will cover using enums to access and assign members and check for equality.

How to Access Members

There are multiple methods for accessing members of an enum. These include the dot syntax, parentheses, and square bracket syntax. Here’s an example to demonstrate the above:

from enum import Enum

# Creating an enum
class Day(Enum):
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY = range(1, 8)

# Accessing enum members
# 1. Using dot syntax
print(Day.SUNDAY)

# 2. Using square brackets
print(Day["MONDAY"])

# 3. Using the parentheses
print(Day(3))

After accessing an enum member, you can store it in a variable. Note that accessing a member gives you a reference to the member object, not its value or name. This is important to remember in the next few sections.

Accessing the Name and Value

As mentioned earlier, when you access an enum member, you create a reference to the member object. If you want to, for some reason, access the name or the value of the enum object, you can use the name and value properties on the object.

print(Day.SUNDAY.name, Day.SUNDAY.value)
<img alt="Enums-Example-2-1" data- data-src="https://kirelos.com/wp-content/uploads/2023/08/echo/Enums-Example-2-1.png/w=786" data- decoding="async" height="533" src="data:image/svg xml,” width=”786″>

Checking for Equality

Recall that assigning an enum member to a variable creates a reference to the enum member object. Therefore, to check if a variable has a particular enum member, we use the is operator to check if the enum member and the variable point to the same object.

Here’s an example to demonstrate:

today = Day.WEDNESDAY

if today is Day.MONDAY:
    print("It's a Monday, :(")

if today is Day.WEDNESDAY:
    print("Happy Wednesday")
<img alt="Enums-example-4-1" data- data-src="https://kirelos.com/wp-content/uploads/2023/08/echo/Enums-example-4-1.png/w=786" data- decoding="async" height="533" src="data:image/svg xml,” width=”786″>

Alternatively, you can use the == operator. On superclasses of the Enum class, the == operator is a wrapper for the is operator. This is done using operator overloading. You can read more about it in this article on Magic Methods. Anyway, here is an example that uses == instead of is.

today = Day.WEDNESDAY

if today == Day.MONDAY:
    print("It's a Monday, :(")

if today == Day.WEDNESDAY:
    print("Happy Wednesday")
<img alt="Enums-example-4-1" data- data-src="https://kirelos.com/wp-content/uploads/2023/08/echo/Enums-example-4-1.png/w=786" data- decoding="async" height="533" src="data:image/svg xml,” width=”786″>

At the risk of being repetitive, enum comparisons check for object identity, not the values.

Final Words

This article covered what enums are and why they are useful. We also covered the different methods to create enums by subclassing the Enum class and using the functional API.

In addition, we covered how to use enums, access values, and make comparisons. Next, you may want to read our article on TypeScript enums.