Enumerations in Python are implemented by using the module named "enum". Enumerations are created using classes. Enums have names and values associated with them. Let's cover the different concepts of Python Enum in this article.
What are Enums and Why are they useful?
Enumerations or Enums is a set of symbolic names bound to unique values. It can be iterated over to return its canonical members in definition order. It provides a way to create more readable and self-documenting code by using meaningful names instead of arbitrary values.
Properties of Enum
- Enums can be displayed as string or repr.
- Enums can be checked for their types using type().
- The "name" keyword is used to display the name of the enum member.
What are the Advantages of Enum
Some of the advantages of using enums include:
- Ease of maintenance: Enums centralize the definition of name values which makes it easier to upgrade or extend the set of values as per our requirements.
- Readability and Self-Documentation: Enums provide meaningful names to values, making the code more human-readable and self-explanatory.
- Type safety: Enums provide some level of type safety, ensuring that only valid values can be used.
- Reduced risk of errors: Enums help prevent the use of incorrect or inconsistent values in your code, reducing the risk of bugs and errors.
Enum class in Python
Python code to demonstrate enumerations
This code defines an enumeration class Season
with four members: SPRING, SUMMER, AUTUMN, and WINTER. It showcases key properties of the enum, such as accessing an enum member, its name, and value. Additionally, it demonstrates how to obtain a list of all enum members. The output reflects the name, value, type, and a list of all Season
enum members.
Python
from enum import Enum
class Season(Enum):
SPRING = 1
SUMMER = 2
AUTUMN = 3
WINTER = 4
print(Season.SPRING)
print(Season.SPRING.name)
print(Season.SPRING.value)
print(type(Season.SPRING))
print(repr(Season.SPRING))
print(list(Season))
Output:
Season.SPRING
SPRING
1
<enum 'Season'>
<Season.SPRING: 1>
[<Season.SPRING: 1>, <Season.SUMMER: 2>, <Season.AUTUMN: 3>, <Season.WINTER: 4>]
Accessing Modes
Enum members can be accessed in two ways:
- By value:- In this method, the value of enum member is passed.
- By name:- In this method, the name of the enum member is passed.
A separate value or name can also be accessed using the "name" or "value" keyword.
The code defines an enumeration class 'Season'
with four members. It showcases how to access enum members by value and name. It demonstrates that you can obtain an enum member by specifying its value or name, and then access its name or value accordingly. This code provides examples for both value-based and name-based enum member access.
Python
from enum import Enum
class Season(Enum):
SPRING = 1
SUMMER = 2
AUTUMN = 3
WINTER = 4
print("The enum member associated with value 2 is : ", Season(2).name)
print("The enum member associated with name AUTUMN is : ", Season['AUTUMN'].value)
Output:
The enum member associated with value 2 is : SUMMER
The enum member associated with name AUTUMN is : 3
Enumerations are iterable. They can be iterated using loops
In this example, we will use for loop to print all the members of the Enum class.
The code defines an enumeration class 'Season'
with four members. It iterates through the enum members and prints their values and names. The output displays each enum member's value and its fully-qualified name, providing a way to work with and display enum values.
Python
from enum import Enum
class Season(Enum):
SPRING = 1
SUMMER = 2
AUTUMN = 3
WINTER = 4
for season in (Season):
print(season.value,"-",season)
Output:
1 - Season.SPRING
2 - Season.SUMMER
3 - Season.AUTUMN
4 - Season.WINTER
Enumerations Support Hashing
In this example, we will show how users can hash the Enum class that can be used in dictionaries or sets.
This code uses the 'enum'
module to define an enumeration class 'Animal'
with three members: dog, cat, and lion. It then creates a dictionary di
and assigns values to it based on enum members. Finally, it checks if the dictionary matches a specific key-value pair.
Python
import enum
class Animal(enum.Enum):
dog = 1
cat = 2
lion = 3
di = {}
di[Animal.dog] = 'bark'
di[Animal.lion] = 'roar'
if di == {Animal.dog: 'bark', Animal.lion: 'roar'}:
print("Enum is hashed")
else:
print("Enum is not hashed")
Output:
Enum is hashed
Compare Enums in Python
Enumerations support two types of comparisons, that are:
- Identity:- These are checked using keywords "is" and "is not".
- Equality :- Equality comparisons of "==" and "!=" types are also supported.
This code defines an enumeration class Animal
using the enum
module with three members: dog, cat, and lion. It then performs comparisons between enum members to check for equality and inequality.
Python
import enum
class Animal(enum.Enum):
dog = 1
cat = 2
lion = 3
if Animal.dog is Animal.cat:
print("Dog and cat are same animals")
else:
print("Dog and cat are different animals")
if Animal.lion != Animal.cat:
print("Lions and cat are different")
else:
print("Lions and cat are same")
Output:
Dog and cat are different animals
Lions and cat are different
Similar Reads
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
enum.IntEnum in Python With the help of enum.IntEnum() method, we can get the enumeration based on integer value, if we compare with normal enum based class it will fail by using enum.IntEnum() method. Syntax : enum.IntEnum Return : IntEnum doesn't have a written type. Example #1 : In this example we can see that by using
1 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
howdoi in Python howdoi is a command-line tool written in Python. It gives the answers to do basic programming tasks, while working still in the console, directly from the command line. It scrapes code from the top answers on StackOverflow. You need an internet connection for using howdoi. howdoi will answer all sor
2 min read
Python 3 basics Python was developed by Guido van Rossum in the early 1990s and its latest version is 3.11.0, we can simply call it Python3. Python 3.0 was released in 2008. and is interpreted language i.e it's not compiled and the interpreter will check the code line by line. This article can be used to learn the
10 min read
Python Features Python is a dynamic, high-level, free open source, and interpreted programming language. It supports object-oriented programming as well as procedural-oriented programming. In Python, we don't need to declare the type of variable because it is a dynamically typed language. For example, x = 10 Here,
5 min read
External Modules in Python Python is one of the most popular programming languages because of its vast collection of modules which make the work of developers easy and save time from writing the code for a particular task for their program. Python provides various types of modules which include built-in modules and external m
5 min read
Python List Exercise List OperationsAccess List ItemChange List itemReplace Values in a List in PythonAppend Items to a listInsert Items to a listExtend Items to a listRemove Item from a listClear entire listBasic List programsMaximum of two numbersWays to find length of listMinimum of two numbersTo interchange first an
3 min read
Python in Keyword The in keyword in Python is a powerful operator used for membership testing and iteration. It helps determine whether an element exists within a given sequence, such as a list, tuple, string, set or dictionary.Example:Pythons = "Geeks for geeks" if "for" in s: print("found") else: print("not found")
3 min read