- Python Basics
- Python Home
- Python History
- Python Applications
- Python Features
- Python Versions
- Python Environment Setup
- Python Basic Syntax
- Python end (end=)
- Python sep (sep=)
- Python Comments
- Python Identifiers
- Python Variables
- Python Operators
- Python Ternary Operator
- Python Operator Precedence
- Python Control & Decision
- Python Decision Making
- Python if elif else
- Python Loops
- Python for Loop
- Python while Loop
- Python break Statement
- Python continue Statement
- Python pass Statement
- Python break Vs continue
- Python pass Vs continue
- Python Built-in Types
- Python Data Types
- Python Lists
- Python Tuples
- Python Sets
- Python frozenset
- Python Dictionary
- List Vs Tuple Vs Dict Vs Set
- Python Numbers
- Python Strings
- Python bytes
- Python bytearray
- Python memoryview
- Python Misc Topics
- Python Functions
- Python Variable Scope
- Python Enumeration
- Python import Statement
- Python Modules
- Python operator Module
- Python os Module
- Python Date & Time
- Python Exception Handling
- Python File Handling
- Python Advanced
- Python Classes & Objects
- Python @classmethod Decorator
- Python @staticmethod Decorator
- Python Class Vs Static Method
- Python @property Decorator
- Python Regular Expressions
- Python CGI Programming
- Python Network Programming
- Python Send E-mail
- Python Multi-threading
- Python XML Processing
- Python MySQL Database
- Python GUI Programming
- Python Event Handling
- Python Keywords
- Python All Keywords
- Python and
- Python or
- Python not
- Python True
- Python False
- Python None
- Python in
- Python is
- Python as
- Python with
- Python yield
- Python return
- Python del
- Python from
- Python lambda
- Python assert
- Python Built-in Functions
- Python All Built-in Functions
- Python print() Function
- Python input() Function
- Python int() Function
- Python len() Function
- Python range() Function
- Python str() Function
- Python ord() Function
- Python chr() Function
- Python read()
- Python write()
- Python open()
- Python Examples
- Python Examples
- Python Test
- Python Online Test
- Give Online Test
- All Test List
Python enum (Enumeration)
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
- Enumeration Methods and Properties
- Example to implement methods and properties of enumeration
- Example to implement enumeration
- Print all enumeration values using enum iteration
- Print all enumeration Item in name - value pairs
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:
- The class named OrderCount is an enumeration (or enum in short)
- The attributes OrderCount.LAPTOP, OrderCount.MOBILE, etc., are enumeration (enum) members, that are functionally constants
- As you can see, enumerations comes in names and values pair
- The name of OrderCount.LAPTOP is LAPTOP, and the value of OrderCount.LAPTOP is 3
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.
- 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. - 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 - 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) - 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. - 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:
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:
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:
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:
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:
« Previous Tutorial Next Tutorial »