Reputation: 21
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)
Upvotes: 1
Views: 84
Reputation: 35512
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)
Upvotes: 7
Reputation: 708
You can try to use exec function:
def schedule_tasks(day, time):
exec("schedule.every().{0}.at({1}).do(job)".format(day, time))
Upvotes: -3