Rinaldo Fowler

How to use Python Enums


A lot of boolean checks get written like questions. This works somewhat okay because we can map yes to true and no to false, kinda. Problems appear when we try to use this mapping with negative questions: is_not_cold. In this case it seems like true maps to warm or not cold, and false maps to cold. But it's easy to miss the "not" in that title. Further, when the boolean result is removed from the "question" it's hard to remember what the boolean means.

An alternative to this is the Enum, which lets you enumerate the answers to a question in a meaningful way. Can I find it in the hole?

from enum import Enum

class InHole(Enum):
    FOUND = 1
    NOT_FOUND = 2

What are roles on the team?

class Role(Enum):
    MANAGER = 1
    ADMIN = 2

if check_role("Bob") == Role.ADMIN: