Skip to main content
Editor

Python Enums: Type-Safe Constants for Cleaner Code

Intermediate20 min5 exercises80 XP
0/5 exercises

Imagine you're building a card game. You need to represent the four suits: hearts, diamonds, clubs, and spades. You could use plain strings like "hearts", but what happens when someone types "Hearts" or "hart"? Your code breaks silently.

Python's enum module solves this by letting you define a fixed set of named constants. An Enum (short for enumeration) is a class where each member has a name and a value, and you can't accidentally create invalid members.

In this tutorial, you'll learn to create basic enums, use auto() for automatic values, work with IntEnum and Flag, add methods to enums, and apply practical patterns you'll use in real projects.

How Do You Create a Basic Enum?

An enum is a class that inherits from Enum. Each member is defined as a class attribute with a value. Once created, the members are fixed -- you can't add, remove, or change them.

Creating and accessing enum members
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
# Access by name or value
print(Color.RED)
print(Color.RED.name)
print(Color.RED.value)
# Access by value using the class as a callable
print(Color(2))
# Access by name using bracket notation
print(Color['BLUE'])
Output
Color.RED
RED
1
Color.GREEN
Color.BLUE

Each enum member has two key attributes: .name (the string name like "RED") and .value (the assigned value like 1). You can look up members by name with bracket notation Color['RED'] or by value with callable notation Color(1).


How Do You Compare and Iterate Over Enums?

Enums shine when you use them in if statements and loops. You can compare members with == or is, and iterate over all members of an enum class.

Comparing and iterating over enums
from enum import Enum
class Status(Enum):
PENDING = 'pending'
ACTIVE = 'active'
INACTIVE = 'inactive'
BANNED = 'banned'
# Comparison
user_status = Status.ACTIVE
if user_status == Status.ACTIVE:
print('User is active')
if user_status is not Status.BANNED:
print('User is not banned')
# Iteration
print('\nAll statuses:')
for status in Status:
print(f' {status.name} -> {status.value}')
Output
User is active
User is not banned

All statuses:
  PENDING -> pending
  ACTIVE -> active
  INACTIVE -> inactive
  BANNED -> banned
Without Enum (fragile)
# Typos cause silent bugs
status = 'actve'  # oops
if status == 'active':
    print('Active')  # never runs!
With Enum (safe)
from enum import Enum

class Status(Enum):
    ACTIVE = 'active'

status = Status.ACTIVE
# Status.ACTVE would raise AttributeError!

What Are auto(), IntEnum, and @unique?

When the exact value doesn't matter, auto() generates values automatically. IntEnum creates enums whose members behave like integers -- useful when you need to do math or pass them to APIs that expect numbers. The @unique decorator prevents duplicate values.

auto(), IntEnum, and sorting
from enum import Enum, IntEnum, auto, unique
# auto() generates values for you
class Direction(Enum):
NORTH = auto()
SOUTH = auto()
EAST = auto()
WEST = auto()
print('Direction values:')
for d in Direction:
print(f' {d.name} = {d.value}')
# IntEnum members work as integers
class Priority(IntEnum):
LOW = 1
MEDIUM = 2
HIGH = 3
CRITICAL = 4
# Can compare with integers and sort
print(f'\nHIGH > LOW: {Priority.HIGH > Priority.LOW}')
print(f'MEDIUM + 1 = {Priority.MEDIUM + 1}')
tasks = [Priority.HIGH, Priority.LOW, Priority.CRITICAL]
print(f'Sorted: {sorted(tasks)}')
Output
Direction values:
  NORTH = 1
  SOUTH = 2
  EAST = 3
  WEST = 4

HIGH > LOW: True
MEDIUM + 1 = 3
Sorted: [<Priority.LOW: 1>, <Priority.HIGH: 3>, <Priority.CRITICAL: 4>]
@unique prevents duplicate values
from enum import Enum, unique
# @unique prevents duplicate values
try:
@unique
class Shape(Enum):
SQUARE = 1
DIAMOND = 1 # duplicate value!
CIRCLE = 2
except ValueError as e:
print(f'Error: {e}')
Output
Error: duplicate values found in <enum 'Shape'>: DIAMOND -> SQUARE

Can Enums Have Methods?

Since enums are classes, you can add methods and properties to them. This lets you attach behavior directly to each member, keeping related logic together instead of scattering if/elif chains across your code.

Enums with methods and properties
from enum import Enum
class Suit(Enum):
HEARTS = 'hearts'
DIAMONDS = 'diamonds'
CLUBS = 'clubs'
SPADES = 'spades'
@property
def color(self):
if self in (Suit.HEARTS, Suit.DIAMONDS):
return 'red'
return 'black'
@property
def symbol(self):
symbols = {
Suit.HEARTS: 'H',
Suit.DIAMONDS: 'D',
Suit.CLUBS: 'C',
Suit.SPADES: 'S',
}
return symbols[self]
for suit in Suit:
print(f'{suit.symbol} {suit.name}: {suit.color}')
Output
H HEARTS: red
D DIAMONDS: red
C CLUBS: black
S SPADES: black

What Are Common Enum Patterns in Real Code?

Enums appear everywhere in professional Python code. Here are two patterns you'll encounter often: using enums as dictionary keys, and converting between enums and strings (useful for APIs and databases).

Enums as dictionary keys and string conversion
from enum import Enum
class Size(Enum):
SMALL = 'S'
MEDIUM = 'M'
LARGE = 'L'
XLARGE = 'XL'
# Enums as dictionary keys
pricing = {
Size.SMALL: 9.99,
Size.MEDIUM: 12.99,
Size.LARGE: 15.99,
Size.XLARGE: 18.99,
}
order_size = Size.LARGE
print(f'{order_size.name} costs ${pricing[order_size]}')
# Converting string to enum (useful for API input)
user_choice = 'M'
selected = Size(user_choice)
print(f'Selected: {selected.name} ({selected.value})')
# Listing all valid options (useful for validation messages)
valid = [s.value for s in Size]
print(f'Valid sizes: {valid}')
Output
LARGE costs $15.99
Selected: MEDIUM (M)
Valid sizes: ['S', 'M', 'L', 'XL']

Enums are hashable, so they work perfectly as dictionary keys. This replaces messy if/elif chains with clean, O(1) lookups. When you receive user input as a string, Size(value) converts it back to the enum member (raising ValueError if the value is invalid).


Practice Exercises

Create a Traffic Light Enum
Write Code

Create an Enum called TrafficLight with members RED, YELLOW, and GREEN having string values "stop", "caution", and "go". Then print each member's name and value on separate lines in the format NAME: value.

from enum import Enum
# Define TrafficLight enum here
# Print each member
Predict the Enum Output
Predict Output

What will this code print? Think carefully about how enum comparison works and what auto() assigns.

from enum import Enum, auto
class Season(Enum):
SPRING = auto()
SUMMER = auto()
FALL = auto()
WINTER = auto()
print(Season.SPRING.value)
print(Season.WINTER.value)
print(Season.SUMMER == Season.SUMMER)
print(Season.SUMMER == 2)
HTTP Status Enum with Methods
Write Code

Create an Enum called HTTPStatus with members OK = 200, NOT_FOUND = 404, and SERVER_ERROR = 500. Add a property called is_error that returns True if the value is 400 or above. Print each status and whether it's an error.

from enum import Enum
class HTTPStatus(Enum):
# Define members and is_error property
pass
for status in HTTPStatus:
print(f'{status.name} ({status.value}): error={status.is_error}')
Fix the Enum Bug
Fix the Bug

This code tries to look up a role from a user-submitted string, but it crashes. Fix the code so it correctly converts the string "admin" into the matching Role enum member and prints its name. Don't change the Role definition.

from enum import Enum
class Role(Enum):
ADMIN = 'admin'
EDITOR = 'editor'
VIEWER = 'viewer'
# Bug: This crashes! Fix it.
user_input = 'admin'
role = Role[user_input]
print(role.name)
Build a Permission System
Write Code

Create an IntEnum called Permission with READ = 1, WRITE = 2, DELETE = 4, and ADMIN = 7. Write a function check_permissions(user_level, required) that returns True if the user's permission level includes the required permission using bitwise AND (&). Test with the cases shown in the starter code.

from enum import IntEnum
class Permission(IntEnum):
# Define the permission levels
pass
def check_permissions(user_level, required):
# Use bitwise AND to check if required permission is included
pass
# Test cases
print(check_permissions(Permission.ADMIN, Permission.READ))
print(check_permissions(Permission.ADMIN, Permission.DELETE))
print(check_permissions(Permission.WRITE, Permission.DELETE))
print(check_permissions(Permission.READ | Permission.WRITE, Permission.WRITE))

Harder problems

More problems on this topic: Classes

Related Tutorials

Was this tutorial helpful?