codescracker
python

Python enum (Enumeration)



« Python Tutorial Python Examples »

This article is created to provide you the easy way to learn enum (enumeration) in Python with the help of practical example. This article deals with:

Enumeration Definition and Description

In Python, enumeration is nothing but a set of some symbolic names bound to unique and constant values. An enumeration in Python can be iterated. The example to show, how enumeration in Python can be iterated, is shown later on, in this page.

The enum module is used to implement enumeration in Python. And classes are used to create enumerations like shown in the code block given below:

from enum import Enum
class OrderCount(Enum):
    LAPTOP = 3
    MOBILE = 6
    TV = 2

Note - In above example, I've written all the enum members in UPPERCASE letters, because enumeration are used to represent constants. And it is better practice to write any variable that holds constant values, in UPPERCASE. Otherwise, it is up to you, whether to use UPPERCASE, LOWERCASE or COMBINATION of UPPER and LOWERCASE.

In above example of enumeration:

Enumeration Methods and Properties

Now we've to learn these 5 things that are most widely used in Python enumerations. I've taken the above short block of code in my mind while evaluating these things with the help of example to provide you the clear concept on the topic.

  1. repr() - returns the official string representation of the value that is being passed. For example, print(repr(OrderCount.LAPTOP)) produces <OrderCount.LAPTOP: 3> as output from above example. That is, enumeration members have human readable string representation. But using the repr(), we will be able to fetch the official or detailed version of the string.
  2. type() - returns the enumeration's name that the enumeration member belongs to. For example, print(type(OrderCount.LAPTOP)) produces <enum 'OrderCount'> as output. That shows OrderCount.LAPTOP enum member belongs to OrderCount enum
  3. isinstance() - returns TRUE if the specified object (first argument) is an instance of class (second argument). Otherwise returns FALSE. For example, print(isinstance(OrderCount.LAPTOP, OrderCount)) produces TRUE as output, since the OrderCount.LAPTOP (first argument) is an instance of the class named OrderCount (the second argument)
  4. name - In Python, enum members have a property that contains the name of the item. For example, print(OrderCount.LAPTOP.name) produces LAPTOP as output. That is the name of the enum item.
  5. value - In Python, enum members also have a property that contains the value of the item. For example, print(OrderCount.LAPTOP.value) produces 3 as output.

Example to use Methods and Properties of Enumeration

The program given below uses repr(), type(), isinstance(), name and value in one single program. Let's have a look at the program given below and understand it in practical way after seeing its sample output:

from enum import Enum

class OrderCount(Enum):
    LAPTOP = 3
    MOBILE = 6
    TV = 2

print(repr(OrderCount.LAPTOP))
print(type(OrderCount.LAPTOP))
print(isinstance(OrderCount.LAPTOP, OrderCount))
print(OrderCount.LAPTOP.name)
print(OrderCount.LAPTOP.value)

Here is its sample output:

python enum

Example to Implement Enumeration

Now let's take a look at the program given below that demonstrates enumeration in practical way. This is basically the modified version of previous program. Since this program includes description of each output:

from enum import Enum

class OrderCount(Enum):
    LAPTOP = 3
    MOBILE = 6
    TV = 2

print("The string representation of enum member \"OrderCount.MOBILE\" is:", OrderCount.MOBILE)
print("The \"repr\" representation of enum member \"OrderCount.MOBILE\" is:", repr(OrderCount.MOBILE))
print("The name of enum member \"OrderCount.MOBILE\" is:", OrderCount.MOBILE.name)
print("The value of enum member \"OrderCount.MOBILE\" is:", OrderCount.MOBILE.value)

The snapshot given below shows its sample output:

python enumeration

Print all Enumeration Values

This example is created in a way that, it will create an enumeration and then prints all the values of enumeration:

from enum import Enum

class OrderCount(Enum):
    LAPTOP = 3
    MOBILE = 6
    TV = 2

print("All enum values are:")
for val in OrderCount:
    print(val.value)

This program produces the output that looks like:

python example print all enum values

Print all Enumeration Item in Name - Value Pair

Basically this is the modified and improved version of previous program. Since this program prints all enumeration item's names along with its values in an organized way:

from enum import Enum

class OrderCount(Enum):
    LAPTOP = 3
    MOBILE = 6
    TABLET = 2

print("All enum Names - values are:")
print("\nName\t\tValue")
print("-----------------")
for val in OrderCount:
    print(val.name, "\t\t", val.value)

And the snapshot given below shows the sample output produced by above Python program:

python print enumeration name value pair

Enumeration Members are Hashable

Since enumeration members in Python are hashable, therefore we can use enum members in dictionaries or sets. If any object never changes its value during its lifetime, then the object is called as hashable object. In other words, hashability enables an object to be usable as a dictionary key and a set member.

The example program given below illustrates all the things said here to support enum members are hashable.

from enum import Enum

class Product(Enum):
    MOBILE = 3
    LAPTOP = 6
    TABLET = 5

product_dict = {}
product_dict[Product.MOBILE] = 'white'
product_dict[Product.LAPTOP] = 'black'

if product_dict == {Product.MOBILE: 'white', Product.LAPTOP: 'black'}:
    print("Enum members are hashable")
else:
    print("Enum members are not hashable")

The snapshot given below shows sample output produced by this Python program:

python enum members are hashable example

Python Online Test


« Python Tutorial Python Examples »



© Copyright 2021. All Rights Reserved.

CodesCracker