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 Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

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