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
-

Facing issues? Have Questions? Post them here! I am happy to answer!


Author: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap