This article will cover a guide on using “Enum” objects in Python. An enum or an “enumeration” class allows you to create unique constants whose value remains unchanged in Python programs and applications. All code samples in this article are tested with Python 3.9.5 on Ubuntu 21.04.

About Python Enums

As stated earlier, Enums are objects having constant values. They have symbolic or representational names attached to their respective values. They are in a way similar to other Python variables, but come with some unique features like type-safe objects and grouping. In Python, enums are always represented using upper case characters to indicate that they have constant values. Enums are specially useful in cases when you have a predefined range of possible values and you need to pick and refer to limited choices in your program logic. The usage of Enums in Python can be best understood through examples. Some of them are explained below.

Creating Enums

You can create enums by constructing a new class that inherits the Enum class itself. Have a look at the code sample below:

from enum import Enum

class Color(Enum):


    YELLOW = 1


    BLACK = 2


    WHITE = 3


    PURPLE = 4


    ORANGE = 5

print (Color(1))

print (repr(Color(1)))

print (Color.YELLOW)

print (type(Color.YELLOW))

print (Color.YELLOW.name)

print (Color.YELLOW.value)

The first statement imports the Enum class from the enum module. Next a new class called “Color” is constructed by inheriting the Enum class. Some variables (enum members) are then created having constant values. These variables represent five possible choices. The next few print statements show how you can access these enums, their names and values. These statements are self explanatory. To access a possible enum choice, you can use dot notation or supply a known value as an argument to the class. After running the above code sample, you should get the following output:

Color.YELLOW

Color.YELLOW

YELLOW

1

As you can see in the output, there are a variety of ways you can access enum members. Note that calling print function on an enum will return its human readable string form and not its value. So referring to Color.YELLOW will return Color.YELLOW and not 1.

Iterating Through Enums

You can iterate through an enum type object and get its members using loop statements.

from enum import Enum

class Color(Enum):


    YELLOW = 1


    BLACK = 2


    WHITE = 3


    PURPLE = 4


    ORANGE = 5

for c in Color:


    print (c.name, c.value)

Using the “c” variable, you can access every member of the Color enum type object. After running the above code sample, you should get the following output.

YELLOW 1


BLACK 2


WHITE 3


PURPLE 4


ORANGE 5

Name of Enum Members Must be Unique but Duplicate Values are Allowed

You cannot create two enum members with the same name but their values have no such restrictions. The following code sample will throw an error as there are two enum members with same names.

from enum import Enum

class Color(Enum):


    BLACK = 1


    BLACK = 2


    WHITE = 3


    PURPLE = 4


    ORANGE = 5

After running the above code sample you should get an error similar to this:

File “https://linuxhint.com/usr/lib/python3.9/enum.py”, line 133, in __setitem__


    raise TypeError(‘Attempted to reuse key: %r’ % key)

TypeError: Attempted to reuse key: ‘BLACK’

As you can see in the output, duplicate names are not allowed for enum members. However, the following code is valid where two enum members have the same values.

from enum import Enum

class Color(Enum):


    YELLOW = 2


    BLACK = 2


    WHITE = 3


    PURPLE = 4


    ORANGE = 5

If you also want to force unique values for enum members along with their names, you can use “unique” decorator to prevent duplicate values.

from enum import Enum, unique

@unique

class Color(Enum):


    YELLOW = 2


    BLACK = 2


    WHITE = 3


    PURPLE = 4


    ORANGE = 5

The “@unique” decorator forces enum type objects to throw an error when there are duplicate values assigned to enum members. After running the above code sample, you should get the following output:

File “https://linuxhint.com/usr/lib/python3.9/enum.py”, line 989, in unique


    raise ValueError(‘duplicate values found in %r: %s’ %

ValueError: duplicate values found in : BLACK –> YELLOW

Auto Assign Values to Enum Members

If the values of enum members don’t matter to you, you can use the “auto” method available in the enum module to automatically assign sequential numbers to enum members.

from enum import Enum, auto

class Color(Enum):


    YELLOW = auto()


    BLACK = auto()


    WHITE = auto()


    PURPLE = auto()


    ORANGE = auto()

for c in Color:


    print (c.name, c.value)

As you can see in the code sample aboved, instead of explicitly assigning some values to enum members, auto function has been called while creating each member. The auto method always assigns 1 as the first value. After running the above code sample, you should get the following output:

YELLOW 1


BLACK 2


WHITE 3


PURPLE 4


ORANGE 5

Conclusion

Enums type objects in Python allow you to create constant style variables having unique names. These variables, usually called enum members, can be represented by human readable strings. Enums are especially useful when you want to pick one or more choices from a group of limited options.

About the author

<img data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/09/echo/Cartoon-Man-Avatar-2-150×150.png6133dc65a0ad7.jpg" height="112" src="data:image/svg xml,” width=”112″>

Nitesh Kumar

I am a freelancer software developer and content writer who loves Linux, open source software and the free software community.