DEV Community

Vladimir Ignatev
Vladimir Ignatev

Posted on • Edited on

🤔 Python Quiz: Enums in Python

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)
Enter fullscreen mode Exit fullscreen mode

Sample 2

class Color:
    RED = 1
    GREEN = 2
    BLUE = 3

favorite_color = Color.RED
print(favorite_color.name, favorite_color.value)
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
vladignatyev profile image
Vladimir Ignatev

Enums in Python explained

The correct answer is Sample 1.

In Sample 1, we correctly use the enum module to define an enumeration class Color. By inheriting from Enum, each member of the Color class is turned into an enumeration instance, each with a name (like 'RED') and a value (like 1). 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 the Color class in Sample 2 are just class attributes. They do not have the name and value attributes that a true enum 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 the enum module.