enum in Python

In Python, you can implement an enumeration using the enum module, which provides a way to create named constant values that have a meaningful representation. Enumerations make your code more readable and maintainable by providing a clear and self-explanatory way to define and use constant values.

Implement an enumeration using the enum module

from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 print(Color.RED) # Output: Color.RED print(Color.RED.value) # Output: 1 print(Color.RED.name) # Output: 'RED'

In this example, the Color enumeration is defined with three constant values: RED, GREEN, and BLUE. Each constant is assigned a unique value starting from 1.

Access the enumeration members

You can access the enumeration members using their names (Color.RED) or retrieve their values (Color.RED.value). The .name attribute gives you the string name of the enumeration member.

Enums can also be used in comparisons and loops:

selected_color = Color.GREEN if selected_color == Color.RED: print("Selected color is red") elif selected_color == Color.GREEN: print("Selected color is green") for color in Color: print(color)

Enums can be useful for scenarios where you want to define a set of constant values that are related and have a specific meaning. They help prevent typos, improve code clarity, and make the code more maintainable.

Enforce unique values within the enumeration

If you want to enforce unique values within the enumeration, you can use the @unique decorator from the enum module:

from enum import Enum, unique @unique class Direction(Enum): NORTH = 1 EAST = 2 SOUTH = 3 WEST = 4

This will raise a ValueError if you try to define multiple enumeration members with the same value.


The enum module in Python allows you to implement enumerations, making your code more organized and readable by providing named constants with meaningful values.