Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 8 · Categorical Data with`Enum`

Categorical Data with Enum

Many programs rely on values drawn from a fixed set: user roles, workflow states, product categories, or sentiment labels. Using strings can introduce typos; using integers hides meaning. The Enum class creates symbolic, immutable constants that enforce valid categories.

Signature:

class YourEnum(Enum):
    NAME = value

Here is a simple Enum representing user roles:

from enum import Enum

class Role(Enum):
    ADMIN = 1
    EDITOR = 2
    VIEWER = 3

print(Role.ADMIN)
Listing 364 — Categorical Data with Enum

Output

Role.ADMIN

An unknown member such as Role.ADMNI raises AttributeError, and Role(99) raises ValueError. An enum does not validate every variable automatically; code can still assign a plain string unless you check the input.

In data science, enums are useful when modeling discrete labels:

class Sentiment(Enum):
    POSITIVE = 1
    NEGATIVE = 2
    NEUTRAL = 3
Listing 365 — Categorical Data with Enum

This makes sentiment analysis pipelines cleaner and easier to maintain.

The following challenges combine these structures. Choose the structure from the operation you need: counting, grouping, ordered processing or a fixed set of categories.