Sitemap

Enum python

4 min readSep 14, 2023

--

Press enter or click to view image in full size
Introductory image for Enum in python

What are Enum? How are they used? What benefit do they server? and more…

So, let us discuss about Enum or enumerations, not a new thing you might be coming across (as they are also the part of languages like C, C++ or Java) but I think this is one of the interesting topics to be discussed as this great feature might be under-used and it has other alternatives that are used more frequently.

So let’s start…

Enum, what is this?

Enum in python is a special class, that can help represent a group of immutable values or constants, it further allows creating a more readable and self-documented classes.

Why should I use these?

Ofcourse, why should we use these when we can do the same thing using python dictionary or just a variable? Let’s find out what advantages Enum provide over other methods:

  1. Simplified code — Enum provides a self-documented, more enhanced, readable and streamlined code structure enabling other teammates to understand the code more easily.
  2. Safety — Since the variables defined inside Enum class are immutable, they can be used without worrying of modification anytime in between the code.
  3. Maintenance — Because all the terms or variables are defined at a single place and are immutable they can be maintained only from a single place, providing a huge benefit for the large pieces of code.
  4. Iterable — Iterable? Yes, they are. Just like python list, enum are also iterable.
  5. Hashable — Enum members can hashed and used in dictionaries or sets.

Great, but how do I implement it?

It’s simple.
Enum in python can be implemented using a module named ‘enum’. The Enum class from enum module can be inherited and used within your class. Each variable with in enum class is termed as a member of enum.

Get Jitender Kumar’s stories in your inbox

Join Medium for free to get updates from this writer.

Let us further understand enum with an example:
Say, for example we want to get the richest person from the different countries in our code. So we will define our enum class like:

from enum import Enum

class RichestPerson(Enum):
UNITED_STATES_OF_AMERICA = "Elon Musk"
INDIA = "Mukesh Ambani"
RUSSIA = "Melnichenko"
JAPAN = "Kagemasa Kozuki"
FRANCE = "Bernard Jean"

Okaaay…, how can I use these?

As simple to define that simple it is to use.
We can access both name and value of the enum member.
Let’s see an example:

# 1. Accessing member name
print(RichestPerson.UNITED_STATES_OF_AMERICA.name)
"UNITED_STATES_OF_AMERICA"

# 2. Accessing member value
print(RichestPerson.UNITED_STATES_OF_AMERICA.value)
"Elon Musk"

# 3. Fetching enum member type
print(type(RichestPerson.FRANCE))
<enum 'RichestPerson'>

# 4. Printing enum member as repr
print(repr(RichestPerson.FRANCE))
<RichestPerson.FRANCE: 'Bernard Jean'>
  1. Accessing member name:
    Member name can be accessed using .name
  2. Accessing member value:
    enum member’s value can be accessed using .value
  3. Fetching the enum member type using type()
  4. Printing enum member as repr
  5. Iterating through Enum class
# 5. Iterating through Enum class
for person in (RichestPerson):
print(person.name, ' => ', person.value)

# OUTPUT
UNITED_STATES_OF_AMERICA => Elon Musk
INDIA => Mukesh Ambani
RUSSIA => Melnichenko
JAPAN => Kagemasa Kozuki
FRANCE => Bernard Jean

But, aren’t there other alternatives?

Hmm… correct, there are some alternatives to enum like using constants, namedTuples, dictionary and class constants but these may not provide the same level of functionality and readability as enum.

Let’s check them out too.

Using Constants:
We can use constants, but they are mutable — lacking safety and are also non-iterable.

# Enum alternate: using constants

UNITED_STATES_OF_AMERICA = "Elon Musk"
INDIA = "Mukesh Ambani"
RUSSIA = "Melnichenko"
FRANCE = "Bernard Jean"
JAPAN = "Kagemasa Kozuki"

Using NamedTuples:
can be used as an alternative to enum, but surely they lack readability and self-documenting powers of enum

# Enum alternate: using NamedTuple

from collections import namedtuple
RichestPerson = namedtuple('RichestPerson', ['UNITED_STATES_OF_AMERICA', 'INDIA', 'RUSSIA'])
richest_person = RichestPerson(1, 2, 3)
print(richest_person.UNITED_STATES_OF_AMERICA)
# output: 1
print(richest_person.RUSSIA)
# output: 3

Using Dictionary:
Dictionary can also be used, but similar to constants they lack safety and doesn’t provide auto-iteration

# Enum alternate: using Dictionary

RichestPerson = {
"UNITED_STATES_OF_AMERICA": "Elon Musk",
"INDIA": "Mukesh Ambani",
"RUSSIA": "Melnichenko",
"FRANCE": "Bernard Jean",
"JAPAN": "Kagemasa Kozuki"
}

print(RichestPerson["FRANCE"])
# output: "Bernard Jean"

Using Class Constants:
Class constants might seem a good alternative for enum but still I would prefer enum over class constants as class contants are not truly constants.
However, modifying class constants goes against the intended usage and is not a good practice.

# Enum alternate: using Class Constants

class RichestPerson:
UNITED_STATES_OF_AMERICA = "Elon Musk"
INDIA = "Mukesh Ambani"
RUSSIA = "Melnichenko"
JAPAN = "Kagemasa Kozuki"
FRANCE = "Bernard Jean"

print(RichestPerson.UNITED_STATES_OF_AMERICA)
# output: "Elon Musk"

print(RichestPerson.RUSSIA)
# output: "Melnichenko"

Conclusion

As a conclusion, I would say that being other approaches for defining constants in python, enum stands out as a more superior and organized approah.

Enum provide benefits of encapsulating constants within a dedicated data structure and further ensures highly readable and self-documenting code.
It also comes with built-in iteration, comparison, and string representation functionalities, making them versatile and convenient for various use cases.

Hope you found this article informative. Show your appreciation with an applause.

Thank you

--

--