Enum in python

Enum in python

Advertisement

In Python, an enumeration (enum) is a symbolic name for a set of values. Enums are used to create named constant values, which makes the code more readable and maintainable. Python provides an Enum class in the enum module to create enumerations.

Advertisement

Here’s a simple example:

Advertisement
from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

In this example, Color is an enumeration with three members: RED, GREEN, and BLUE, each assigned a numeric value. You can access these values using dot notation, like Color.RED or Color.BLUE.

Advertisement
print(Color.RED)       # Output: Color.RED
print(Color.RED.value) # Output: 1

Enums can also be iterated:

Advertisement
for color in Color:
    print(color)

This will output:

Advertisement
Color.RED
Color.GREEN
Color.BLUE

Enums provide a way to define named values, which can be more expressive and self-documenting than using raw integers or strings. They help prevent errors that might occur when using arbitrary values and provide a convenient way to represent a fixed set of options or states in your code.

Advertisement
Advertisement

Advertisement

Leave a Comment