Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Object-oriented Programmi...
  5. Enumeration in Python

Enumeration in Python

Enumeration in Python (Enum) is a data type that allows you to define a set of symbolic names bound to unique constant values.

Thank you for reading this post, don't forget to subscribe!
  • It is typically used to represent a fixed set of related constants, such as days of the week, directions, colors, or states.
  • Python provides the enum module to support enumerations.

Syntax and Example:

from enum import Enum

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

# Accessing Enum members
print(Color.RED)         # Output: Color.RED
print(Color.RED.name)    # Output: RED
print(Color.RED.value)   # Output: 1
  • Symbolic Names: Enum members have meaningful names like RED, GREEN, etc.
  • Constant Values: Each member is associated with a constant value.
  • Type-Safe: Prevents invalid or unexpected values.
  • Readable: Improves readability and intent in the code.
  • Improves Code Readability: Replaces ambiguous constants like 1, 2, 3 with descriptive names like Color.RED.
  • Better Maintenance: Makes code easier to maintain by clearly listing all valid values.
  • Prevents Errors: Restricts values to a predefined set, reducing bugs from invalid input.
  • Enforces Valid Choices: Useful in situations where only certain options are valid (e.g., status codes, directions, modes).

How can we help?