Summary: in this tutorial, you’ll learn about Python enumeration and how to use it effectively.
Introduction to the Python Enumeration
By definition, an enumeration is a set of members that have associated unique constant values. Enumeration is often called enum.
Python provides you with the enum
module that contains the Enum
type for defining new enumerations. And you define a new enumeration type by subclassing the Enum
class.
The following example shows how to create an enumeration called Color
:
from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3
Code language: Python (python)
How it works.
First, import the Enum
type from the enum
module:
from enum import Enum
Code language: Python (python)
Second, define the Color
class that inherits from the Enum
type:
class Color(Enum):
Code language: Python (python)
Third, define the members of the Color
enumeration:
RED = 1 GREEN = 2 BLUE = 3
Code language: Python (python)
Note that the enumeration’s members are constants. Therefore, their names are in uppercase letters by convention.
In this example, the Color
is an enumeration. The RED
, GREEN
, and BLUE
are members of the Color
enumeration. They have associated values 1, 2, and 3.
The type of a member is the enumeration to which it belongs.
The following illustrates that the type of Color.RED
is the Color
enumeration:
print(type(Color.RED))
Code language: Python (python)
Output:
<enum 'Color'>
Code language: Python (python)
The Color.RED
is also an instance of the Color
enumeration:
print(isinstance(Color.RED, Color))
Code language: Python (python)
Output:
True
Code language: Python (python)
And it has the name and value attributes:
print(Color.RED.name) print(Color.RED.value)
Code language: Python (python)
Output:
RED 1
Code language: Python (python)
Membership and equality
To check if a member is in an enumeration, you use the in
operator. For example:
if Color.RED in Color: print('Yes')
Code language: Python (python)
Output:
Yes
Code language: Python (python)
To compare two members, you can use either is
or ==
operator. For example:
if Color.RED is Color.BLUE: print('red is blue') else: print('red is not blue')
Code language: Python (python)
Output:
red is not blue
Code language: Python (python)
Note that a member and its associated value are not equal. The following example returns False
:
if Color.RED == 1: print('Color.RED == 1') else: print('Color.RED != 1')
Code language: Python (python)
Output:
Color.RED != 1
Code language: Python (python)
Enumeration members are hashable
Enumeration members are always hashable. It means that you can use the enumeration members as keys in a dictionary or as elements of a Set.
The following example uses the members of the Color
enumeration in a dictionary:
rgb = { Color.RED: '#ff0000', Color.GREEN: '#00ff00', Color.BLUE: '#0000ff' }
Code language: Python (python)
Access an enumeration member by name and value
The typical way to access an enumeration member is to use the dot notation (.) syntax as you have seen so far:Color.RED
Code language: Python (python)
Because the Enum
implements the __getitem__
method, you can also use a square brackets []
syntax to get a member by its name.
For example, the following uses the square brackets []
syntax to get the RED
member of the Color
enumeration by its name:
print(Color['RED'])
Code language: Python (python)
Output:
Color.RED
Code language: Python (python)
Since an enumeration is callable, you can get a member by its value. For example, the following return the RED
member of the Color
enumeration by its value:
print(Color(1))
Code language: Python (python)
Output:
Color.RED
Code language: Python (python)
The following expression returns True
because it accesses the same enumeration member using name and value:
print(Color['RED'] == Color(1))
Code language: Python (python)
Output:
True
Code language: Python (python)
Iterate enumeration members
Enumerations are iterables so you can iterate them using a for
loop. For example:
for color in Color: print(color)
Code language: Python (python)
Output:
Color.RED Color.GREEN Color.BLUE
Code language: Python (python)
Notice that the order of the members is the same as in the enumeration definition.
Also, you can use the list()
function to return a list of members from an enumeration:
print(list(Color))
Code language: Python (python)
Output:
[<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>]
Code language: Python (python)
Enumerations are immutable
Enumerations are immutable. It means you cannot add or remove members once an enumeration is defined. And you also cannot change the member values.
The following example attempts to assign a new member to the Color
enumeration and causes a TypeError
:
Color['YELLOW'] = 4
Code language: Python (python)
Error:
TypeError: 'EnumMeta' object does not support item assignment
Code language: Python (python)
The following example attempts the change the value of the RED
member of the Color
enumeration and causes an AttributeError
:
Color.RED.value = 100
Code language: Python (python)
Output:
AttributeError: can't set attribute
Code language: Python (python)
Inherits from an enumeration
An enumeration cannot be inherited unless it contains no members. The following example works fine because the Color
enumeration contains no members:
class Color(Enum): pass class RGB(Color): RED = 1 GREEN = 2 BLUE = 3
Code language: Python (python)
However, the following example won’t work because the RGB
enumeration has members:
class RGBA(RGB): ALPHA = 4
Code language: Python (python)
Error:
TypeError: Cannot extend enumerations
Code language: Python (python)
Python enumeration example
The following example defines an enumeration called ResponseStatus
:
class ResponseStatus(Enum): PENDING = 'pending' FULFILLED = 'fulfilled' REJECTED = 'rejected'
Code language: Python (python)
Suppose you receive a response from an HTTP request with the following string:
response = '''{ "status":"fulfilled" }'''
Code language: Python (python)
And you want to look up the ResponseStatus
enumeration by the status
. To do that, you need to convert the response’s string to a dictionary and get the value of the status:
import json data = json.loads(response) status = data['status']
Code language: Python (python)
And then you look up the member of the ResponseStatus
enumeration by the status’ value:
print(ResponseStatus(status))
Code language: Python (python)
Output:
PromiseStatus.FULFILLED
Code language: Python (python)
Here’s the complete program:
from enum import Enum import json class ResponseStatus(Enum): PENDING = 'pending' FULFILLED = 'fulfilled' REJECTED = 'rejected' response = '''{ "status":"fulfilled" }''' data = json.loads(response) status = data['status'] print(ResponseStatus(status))
Code language: Python (python)
What if the status
is not one of the values of the ResponseStatus
members? then you’ll get an error. For example:
from enum import Enum import json class ResponseStatus(Enum): PENDING = 'pending' FULFILLED = 'fulfilled' REJECTED = 'rejected' response = '''{ "status":"ok" }''' data = json.loads(response) status = data['status'] print(ResponseStatus(status))
Code language: Python (python)
Error:
ValueError: 'ok' is not a valid ResponseStatus
Code language: Python (python)
To catch the exception, you can use the try…except statement like the following:
from enum import Enum import json class ResponseStatus(Enum): PENDING = 'pending' FULFILLED = 'fulfilled' REJECTED = 'rejected' response = '''{ "status":"ok" }''' data = json.loads(response) status = data['status'] try: if ResponseStatus(status) is ResponseStatus.FULFILLED: print('The request completed successfully') except ValueError as error: print(error)
Leave a Reply