Python
Enum
Programming
Python3
Software Development

How can I represent an 'Enum' in Python?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Python, a versatile and widely-used programming language, introduced the Enum class in version 3.4. The Enum class provides a way to define constants in a structured and readable manner. This guide will explore what an Enum is, how to use it in Python, and its advantages in coding.

Understanding Enums in Python

An Enum (short for Enumeration) is a symbolic name for a set of values, often representing a sequence of related constants. Enums are useful as they provide a clear and effective way to represent a set of named values, which can make code more readable and prevent errors related to using arbitrary constant values directly.

Creating Enums

To create an Enum in Python, you need to import the enum module. Enums are defined by subclassing Enum class from the enum module. Each element in an Enum is unique and immutable – it's like defining a collection of named constants.

Here's a simple example:

python
1from enum import Enum
2
3class Color(Enum):
4    RED = 1
5    GREEN = 2
6    BLUE = 3

In this example, Color is an enumeration with three members: RED, GREEN, and BLUE, each assigned a unique integer.

Accessing Enum Members

Once an Enum is defined, you can access its members in several ways:

python
print(Color.RED)
print(Color.GREEN.name)
print(Color.BLUE.value)

This will output:

 
Color.RED
GREEN
3
  • Color.RED refers to the enum member itself.
  • Color.GREEN.name retrieves the name of the member.
  • Color.BLUE.value gets the assigned value of the member.

Iterating Over Enum Members

Enumerations are iterable, which means you can loop over them:

python
for color in Color:
    print(color)

This will print:

 
Color.RED
Color.GREEN
Color.BLUE

Comparing Enums

Enums offer robust support for member comparison. You can compare enum members using identity (is) and equality (==) checks:

python
1if Color.RED is Color.GREEN:
2    print("This won't print as they are different")
3if Color.RED == Color.RED:
4    print("This will print as they are the same")

Enum with Methods

Enums can also contain methods, just like classes. Here's an example:

python
1from enum import Enum
2
3class Shape(Enum):
4    CIRCLE = 1
5    SQUARE = 2
6    TRIANGLE = 3
7
8    def describe(self):
9        return f"I'm a {self.name.lower()}."
10
11# Using the method
12shape = Shape.CIRCLE
13print(shape.describe())

This will output:

 
I'm a circle.

Enumerations and Type Safety

Enums provide a level of type safety that regular constant definitions in Python don't. Consider this example:

python
1def is_shape_circle(shape: Shape):
2    return shape == Shape.CIRCLE
3
4# Valid use
5print(is_shape_circle(Shape.CIRCLE))  # True
6
7# Invalid use will raise an AttributeError instead of returning False
8try:
9    print(is_shape_circle(3))  # Raises an error
10except AttributeError as e:
11    print(e)

Here, passing a non-enum type to the is_shape_circle function will result in a noticeable error, enhancing code safety.

Table: Key Points About Python Enums

Key PointDescription
DefinitionEnums are a way to define named constants commonly used to denote states.
Unique & ImmutableMembers of an Enum are unique and cannot be changed once set.
IterationEnums are iterable, enabling looping over members.
ComparisonSupports identity and equality checks, enhancing readability and safety.
MethodsEnums can include methods, allowing encapsulation of related behavior.
Type SafetyProvides more type safety than raw constants, helping to reduce errors.

Advanced Enum Usage

Automatic Values

In some cases, you might want to automatically assign values to enum members. Python provides the auto() function to achieve this:

python
1from enum import Enum, auto
2
3class Animal(Enum):
4    DOG = auto()
5    CAT = auto()
6    HORSE = auto()
7
8# Accessing values
9print(Animal.DOG.value)   # Outputs: 1
10print(Animal.CAT.value)   # Outputs: 2

Extending Enums

While Enums are not meant to be extended by default, you can use a mixin with IntEnum or similar strategies for more sophisticated needs.

python
1from enum import IntEnum
2
3class ExtendedAnimal(IntEnum):
4    DOG = 1
5    CAT = 2
6
7class MoreAnimals(ExtendedAnimal):
8    HORSE = 3
9    LION = 4

Conclusion

Enums in Python offer a powerful alternative to the typical approach of defining constants, providing clarity, safety, and flexibility. The enum module is a testament to Python's philosophy of "Readability counts," giving programmers tools to write more understandable and less error-prone code. If you are defining a set of related constants, consider using Enums to leverage these advantages.


Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.