0

I have the code like below:

if text == 'today':
    date1, date2 = dt.today_()
    result, data = ga.get_sessions_today_data(user_id, date1, date2)
    result, data, caption = get_final_caption(result, data, date1, date2, 'hour', 'sessions')
    handle_result(chat_id, result, data, caption)
elif text == 'yesterday':
    date1, date2 = dt.yesterday()
    result, data = ga.get_sessions_today_data(user_id, date1, date2)
    result, data, caption = get_final_caption(result, data, date1, end_date, 'hour', 'sessions')
    handle_result(chat_id, result, data, caption)
...

The code is repeated many-many times, just dt.function() and ga.function() are different. How could I optimize the code?

LA_
  • 19,823
  • 58
  • 172
  • 308

1 Answers1

7

You could make a dictionary containing the functions for each possibility of text. Don't put parentheses after the functions, because you don't want to call them:

options = {"today": dt.today_, "yesterday": dt.yesterday} # etc

Then, you could do this to replace your existing code:

date1, date2 = options[text]() # Get the correct function and call it
result, data = ga.get_sessions_today_data(user_id, date1, date2)
result, data, caption = get_final_caption(result, data, date1, date2, 'hour', 'sessions')
handle_result(chat_id, result, data, caption)
Aaron Christiansen
  • 11,584
  • 5
  • 52
  • 78