How to represent an Enum in Python Programming

If you are new to Python Programming and have a background in other languages such as C# or Java and you are wondering how to represent an Enum in Python. Well, the first thing to know is Enum support was added to Python quite later in version 3.4.

Enum (Enumeration) in Python is a set of symbolic names bound to unique values.

Enums can be created using two ways, 1) by using class syntax, 2) by using function-call syntax


Example: Enum using Class Syntax

class DaysOfWeek:
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

# Accessing enumeration values
print(DaysOfWeek.MONDAY)
print(DaysOfWeek.THURSDAY)
print(DaysOfWeek.SUNDAY) 
Output: 1 4 0


Example: Enum using function-call syntax

def DaysOfWeek():
    return {
        'MONDAY': 1,
        'TUESDAY': 2,
        'WEDNESDAY': 3,
        'THURSDAY': 4,
        'FRIDAY': 5,
        'SATURDAY': 6,
        'SUNDAY': 7
    }

# Accessing enumeration values
days = DaysOfWeek()
print(days['TUESDAY']) 
print(days['WEDNESDAY']) 
print(days['SUNDAY']) 
Output:
Python Panda List of Dataframe output Example

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!