How to use the Python enum module



Enums allow you to set options using code and allow for consistent use of options in code. Let's say you have a function that takes a type param.

def doMath(mathType, num1, num2):
  if mathType == 1:
    return num1 * num2
  elif mathType == 2:
    return num2 / num2

For the code above, the user can specify the type, but there are a few problems. The first problem is that if the user passes in the type, they could type the value incorrectly. For example, doMath(3, 1, 2).

Also, notice that the function call doesn't really describe what is going to happen. We don't know that 3 is not an acceptable value, and why is the value 1 multiple and 2 divide?

We can solve these problems and more with Enums. In this lesson, we will look at the Python enum module.

A Simple Example

We begin by fixing the function above with enums.

## Start by importing the Enum base class
from enum import Enum

## Create a new class to extend the Base
## class and create some Enums
class MathOperations(Enum):
  DIVIDE = 2

## Replace the arbitrary numbers with enums
def doMath(mathType, num1, num2):
  if mathType == MathOperations.MULITPLY:
    return num1 * num2
  elif mathType == MathOperations.DIVIDE:
    return num2 / num2

## Call the function using the new enums
doMath(MathOperations.MULITPLY, 1, 2)

Note, that is it no required to have all uppercase names for your enum, i.e. MULTIPLY, but this is a common convention.


That's the main concept. There are many more features with the enum module, so be sure to check out the official docs: