Explore Courses Blog Tutorials Interview Questions
+1 vote
in Python by (210 points)
Can anyone tell me how I can represent the equivalent of an Enum in Python?

2 Answers

+2 votes
by (10.9k points)
edited by

@Chandini , Enum was added to Python 3.4 and more advanced technques can be used using aenum library.To use aenum ,run $ pip install aenum.


For new versions,

from enum import Enum     

Stationary = Enum('Stationary', 'pen pencil eraser ink')

Stationary.pen   #returns <Stationary.pen:1>

Stationary['pen'] #returns<Stationary.pen : 1> #returns ‘pen’

For earlier versions:

def enum(**enums):

return type('Enum', (), enums)


>>> Num = enum(ZERO='zero',ONE=1, TWO='two')



>>> Num.ONE


>>> Num.TWO


If you are looking for upskilling yourself in python you can join our Python Certification and learn from an industry expert.

0 votes
by (106k points)

Here is one implementation:

class Enum(set):

    def __getattr__(self, name):

        if name in self:

            return name

        raise AttributeError

Here is its usage:

Animals = Enum(["ABC", "DAT", "HOP"])


You can use the following video tutorials to clear all your doubts:-

Related questions

Browse Categories