How to represent Enum in Python?

How to represent Enum in Python?

Do you know what Enum means in the programming field and how to represent Enum in Python? Let’s clear all of Enum today. Enum short for “Enumeration” is a user-defined data type. It allows us to create a set of named values that are constants and can be used as possible options or choices for a variable. These constants once defined, can not be changed later in the program. 

Think of it like a menu in your favorite coffee shop. The menu has different options which you can choose from, and each one has a name that uniquely identifies them with a clear description. In programming, we can define a similar set of values, where each one has a unique identifier and a descriptive name.

Uses of Enumeration

For example, you might use Enum as follows:

  1. Days of the week – Enum can be used to define the seven days of a week.
  2. Months of the year – Similarly, you can define the months in an Enum.
  3. Direction – The four directions East, West, North, and South can be defined in Enum.
  4. Pricing – Enum can be used to define the Price of different items for service.

All the above values are constant means they don’t change. So, they can be defined in Enum and can be used in the program. Using Enum can help developers write more readable, maintainable, and error-free code.

Create Enumeration in Python

Unlike Enum present as a built-in feature in other programming languages such as Java or C++, Python does not have it as a part of its syntax, but from Python 3.4, the Enum module has been introduced in the standard library which can be used to create Enum in Python.

But, if you are using the Python version below 3.4, you have to install the enum34 library.

To install enum34, run pip install enum34 in your terminal. This will install the enum34 library in your system, after which you can use Enum as shown below.

Alternatively, you can also use aenum, which is a third-party library to do slightly advanced stuff with Enum.

There are two ways in which you can define Enumeration in python

1. Using class syntax

You can simply import Enum from the enum module and create a class that inherits from the Enum class. This class can be used as an Enum to represent a set of constant members.

The following example shows how to create an enumeration called Animal –

from enum import Enum
#NOTE: By convention, The name of the members of this class should be in upper-case as they are constants.
class Animal(Enum):
    CAT = 1
    DOG = 2
    BIRD = 3
    FISH = 4

In the above example, the Animal class is an enumeration and the CAT, DOG, BIRD, and FISH are the members of the Animal enumeration with corresponding associated values 1, 2, 3, and 4.

2. Using function-call syntax

from enum import Enum
Color = Enum('Color', ['RED', 'GREEN', 'BLUE'])

Datatype of Enumeration members

The data type of all the members is the Enum class itself, to which the members belong. We can use the type() function to check the Datatype of the member

from enum import Enum
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
favorite_color = Color.RED
print(type(favorite_color))
print(favorite_color.name, favorite_color.value)

Output:

<enum 'Color'>
RED 1

The Color.RED member has two attributes called name and value which can be used to access the corresponding name and value associated with the member.

Access the Enumeration members

We can access the Enumeration members in three ways

1. Access the Enum members using the dot(.) operator as Enum_class.member_name

from enum import Enum
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
print(Color.RED.name + " = " + str(Color.RED.value))

Output:

RED = 1

2. Access the Enum members with [] syntax as Enum_class[member_name]

from enum import Enum
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
print(Color['RED'].name + " = " + str(Color['RED'].value))

Output:

RED = 1

3. We can also access Enum members by using member’s values like this

from enum import Enum
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
print(Color(3))
print(Color(3).name)
print(Color(3).value)

Output:

Color.BLUE
BLUE
3

Iterate the Enum members

Enumerations are iterable so we can use loops to iterate over them. In the below example, we use a for loop to iterate over the Enum class and print all members.

from enum import Enum
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
for color in Color:
    print(color, color.name, color.value)

Output:

Color.RED RED 1
Color.GREEN GREEN 2
Color.BLUE BLUE 3

We can check if a value is in Enumeration by using in operator and to compare two members, we can use the == operator or the is the keyword.

from enum import Enum
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
if(Color.RED in Color):
    print("RED is in Color")
else:
    print("RED is not in Color")
if(Color.BLUE is Color.RED or Color.BLUE == Color.GREEN):
    print("BLUE is RED or GREEN")
else:
    print("BLUE is neither RED nor GREEN")

Output:

RED is in Color
BLUE is neither RED nor GREEN

Enumerations are immutable in nature

Enumerations are immutable, meaning once they are defined, we can’t add, remove or change the value of the Enum members later in the program.

In the below code, we try to set the value attribute of the RED member to 9 but it’s not possible and it throws an error called AttributeError.

from enum import Enum
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
    
Color.RED.value = 9 #set the value of RED to 9

Output:

AttributeError: <enum 'Enum'> cannot set attribute 'value'

Click here to find more discussion on Enum in Python on StackOverflow.

Conclusion

In this article, you have learned about creating Enum in Python, working with Enumeration members, use enumerations with practical examples. With this, you can start using Enums in your Python programs to make them more readable, organized, and maintainable. If you need more information about Enumerations, you can check out the documentation here.

Thank you for visiting our website.


Also read:

Share:

Author: Ayush Purawr