Editor

Build a Permission System

Advanced · Write the code · from Python Enums: Type-Safe Constants for Cleaner Code

From the lesson: Python Enums: Type-Safe Constants for Cleaner Code

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.

Read the lesson

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))

More Enum exercises

All Python exercises · 50 practice problems · Standard Library Essentials quiz