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?

0

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.