Insights from Our Experts

Blog image

How to Implementing Enum in Python

Author Image

Nakul Narayanan,Software Engineer

Enum is a data type consisting of a set of named values called elements, members or enumerators of the type.  These enumerated named values function as constants in the computing language. For instance, a Color enum may include named values like Red, Green, and Yellow. 

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 take a step by step approach in getting things done with enum and more.

Installing “enum” :

Python 3.x has built in type enum if not use pip install enum34.

For creating an enumerated type Card

# Importing enum
import enum

class Cards(enum.Enum):
Creating enumerations
Club = 1
Diamond = 2
Heart = 3
Spade = 4

Or enum could be directly invoked as

Cards = Enum('Cards', ['Club', 'Diamond', 'Heart','Spade'], start=1)

where Cards will be the enum name and ['Club', 'Diamond', 'Heart', 'Spade'] will be the enum members, They could be a list or name-value pairs or dict. Unless the value is not specified the default values will be the list indices (the start indices could be specified explicitly by setting start parameter)

>>> Cards.Club
<Cards.Club: 1>


Read more: What is the Future Scope for Python Django Web Development?

Also read: 7 reasons why Python is the ultimate choice of startups in 2020

Accessing enum values

Enum members can be accessed in 2 ways

1. By name: In this method, the name of the enum member is passed.

print (Cards(2).name >> Diamond)

2. By value: In this method, the value of the enum member is passed.

print (Cards.Diamond.value >>2)

Comparison enum values

1. Identity:- These are checked using keywords “is” and “is not“.

2. Equality:- Equality comparisons of “==” and “!=” types are supported.


  • List (Cards)
    Output as

[<Cards.Club: 1>, <Cards.Diamond: 2>, <Cards.Heart: 3>, <Cards.Spade: 4>]

  • The special attribute “__members__” is an ordered dictionary mapping names to members. It includes all names defined in the enumeration.
for name, member in Cards.__members__.items():
    name, member

Output :

('Club', <Cards.Club: 1>)
('Diamond', <Cards.Diamond: 2>)
('Heart', <Cards.Heart : 3>)
('Spade', <Cards.Spade : 4>)

Uniqueness in value :

If enum members are required to have unique value assignment then "@unique" is added. ValueError exception will be raised if member value repeats.

Syntax for creating enum in Python:

def enum(**named_values):
    return type('Enum', (), named_values)
Cards = enum(CLUB='club', DIAMOND='Diamond', HEART='Heart',SPADE= Spade)
class User(object):
    def __init__(self, gender):
        if gender not in (Gender.MALE, Gender.FEMALE, Gender.N_A):
        raise ValueError('gender not valid')
        self.gender = gender

A small comparison between the enum usage demonstrated here:

class Certificate(Model):
   Permanent= 1
   Temporary= 2
   In_progress= 3
   status= frozenset([PERMANENT, TEMPORARY, IN_PROGRESS])
   author= StringProperty()
   text= TextProperty()
   state= String(choices=STATES)
certificate= Certificate(author="Xion", text="Hey")
certificate.state= Certificate. In_progress

Converting it to use enum

class Certificate(Model):
   class Status(Enum):
       Permanent= 1
       Temporary= 2 
       In_progress= 3
   author= StringProperty()
   text= TextProperty()
   state= StringProperty(choices=[s.value for s in Status])
certificate= Certificate(author="Xion", text="Meh.")
certificate.state= Certificate.Status.In_progress.value

Advantages of enum:

  1. If you use enums instead of integers (or String codes), you increase the compile-time and avoid errors from passing in invalid constants, and document which values are legal to use.

  2. Enums are not allocated in memory, they exist only in the compilation stage.

  3. A new developer could easily understand the variable type and the values that could be allocated for that variable. 

  4. Enhanced readability of code.

  5. If any error is present, it'll be caught in the compilation of code.

  6. An enum that is identical across Python and the database management system can prevent hard-to-find bugs.

  7. Always check the input values before accepting them into your system. It can counter malicious input. 

Note: Overuse of enums can make your methods do too much (it's often better to have several separate methods, rather than one method that takes several flags), but if you have to use flags or type codes enums are the way to go.

Also read: Off-the-shelf v/s Custom-software - Which to choose

Coding is in Sayone’s blood and we aim to write great codes with excellent readability that seamlessly execution of functions. This has been the underlying success behind our mobile and web application development. Reach out to us and our experts will get back to you with some excellent services to offer.


I Need

Help for