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?
JavaScript
x
41
41
1
def schedule_on_monday(time):
2
schedule.every().monday.at(time).do(job)
3
4
5
def schedule_on_tuesday(time):
6
schedule.every().tuesday.at(time).do(job)
7
8
9
def schedule_on_wednesday(time):
10
schedule.every().wednesday.at(time).do(job)
11
12
13
def schedule_on_thursday(time):
14
schedule.every().thursday.at(time).do(job)
15
16
17
def schedule_on_friday(time):
18
schedule.every().friday.at(time).do(job)
19
20
21
def schedule_on_saturday(time):
22
schedule.every().saturday.at(time).do(job)
23
24
25
def schedule_on_sunday(time):
26
schedule.every().sunday.at(time).do(job)
27
28
29
def schedule_tasks(day, time):
30
switcher = {
31
'monday': schedule_on_monday,
32
'tuesday': schedule_on_tuesday,
33
'wednesday': schedule_on_wednesday,
34
'thursday' : schedule_on_thursday,
35
'friday' : schedule_on_friday,
36
'saturday' : schedule_on_saturday,
37
'sunday' : schedule_on_sunday
38
}
39
func = switcher.get(day, lambda: "Invalid")
40
func(time)
41
Advertisement
Answer
You can use getattr
to get the property name from a string:
JavaScript
1
3
1
def schedule_tasks(day, time):
2
getattr(schedule.every(), day).at(time).do(job)
3