It's time for the next Python Quiz!
Follow me to learn 🐍 Python 5-minute a day by answering fun quizzes!
Today's topic is enum
module. PEP 435 introduced the enum
module in Python 3.4, providing support for enumerations in Python.
Enumerations are sets of symbolic names (members) bound to unique, constant values. They are used to make code more descriptive and readable. Enums help to address specific variant or case in your code, without actually relying on the value corresponding to that variant.
Quiz
Which one of these code samples correctly demonstrates the use of Enums in Python?
Sample 1
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
favorite_color = Color.RED
print(favorite_color.name, favorite_color.value)
Sample 2
class Color:
RED = 1
GREEN = 2
BLUE = 3
favorite_color = Color.RED
print(favorite_color.name, favorite_color.value)
Post your answer in the comments – is it 0 for the first sample or 1 for the second! As usual, the correct answer will be explained in the comment.
Or go to the previous quiz instead
Like the quiz? Don't miss the quiz I prepared for tomorrow! Follow me and learn 🐍 Python 5-minute a day!
Top comments (1)
Enums in Python explained
The correct answer is Sample 1.
In Sample 1, we correctly use the
enum
module to define an enumeration classColor
. By inheriting fromEnum
, each member of theColor
class is turned into an enumeration instance, each with aname
(like'RED'
) and avalue
(like1
). This is the recommended way to create enumerable constants in Python as per PEP 435.Sample 2, while it does define a class with constant attributes, does not benefit from the advantages of an
enum
. The members of theColor
class in Sample 2 are just class attributes. They do not have thename
andvalue
attributes that a trueenum
member has, and attempting to access them as shown in the print statement would result in an AttributeError. This approach lacks the readability, safety, and features provided by theenum
module.