Skip to content

Enum

In one line

Enum creates named constants — replacing magic numbers/strings with readable, type-safe symbolic names.

In simple words

An Enum (enumeration) is a class with a fixed set of named constant members. Instead of using magic numbers (status = 2), you use readable names (status = Status.ACTIVE).

Enums prevent invalid values, improve readability, and enable IDE autocomplete. Access members by EnumName.MEMBER or EnumName['MEMBER']. Each member has .name and .value.

Variants: IntEnum (compares with ints), StrEnum (Python 3.11+, string members), Flag/IntFlag (bitwise combinable). Use @unique decorator to forbid duplicate values.

Example

python
from enum import Enum, auto

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

class Status(Enum):
    PENDING = auto()   # Auto-assigns 1
    ACTIVE = auto()    # 2
    CLOSED = auto()    # 3

print(Color.RED)           # Color.RED
print(Color.RED.value)     # 1
print(Color["GREEN"])      # Color.GREEN
print(Status.ACTIVE.name)  # ACTIVE

# Iteration
for c in Color:
    print(c)

Enums give named constants with .name and .value. auto() assigns values automatically. Iterate with for loop.

Common confusions

  • Confused with: constants

    The difference: Plain constants (RED = 1) are just variables with no grouping or type safety — any value can be assigned. Enums group related constants, prevent invalid values, support iteration, and provide .name/.value introspection.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary