Skip to content
Advertisement

How can i make this Python code less repetitive?

I was looking for the way to call different functions based on variable and i came up with this dictionary mapping. I wonder if there is a way to somehow improve it and make it less repetitive?

 def schedule_on_monday(time):
    schedule.every().monday.at(time).do(job)
 

def schedule_on_tuesday(time):
     schedule.every().tuesday.at(time).do(job)
 

def schedule_on_wednesday(time):
    schedule.every().wednesday.at(time).do(job)


def schedule_on_thursday(time):
    schedule.every().thursday.at(time).do(job)


def schedule_on_friday(time):
    schedule.every().friday.at(time).do(job)


def schedule_on_saturday(time):
    schedule.every().saturday.at(time).do(job)


def schedule_on_sunday(time):
    schedule.every().sunday.at(time).do(job)


def schedule_tasks(day, time):
    switcher = {
        'monday': schedule_on_monday,
        'tuesday': schedule_on_tuesday,
        'wednesday': schedule_on_wednesday,
        'thursday' : schedule_on_thursday, 
        'friday' : schedule_on_friday, 
        'saturday' : schedule_on_saturday, 
        'sunday' : schedule_on_sunday
    }
    func = switcher.get(day, lambda: "Invalid")
    func(time)

Advertisement

Answer

You can use getattr to get the property name from a string:

def schedule_tasks(day, time):
    getattr(schedule.every(), day).at(time).do(job)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement