Home > Back-end >  How to refactor many ifs and else with different conditions in python?
How to refactor many ifs and else with different conditions in python?

Time:12-02

I have many ifs and elses that assign a variable an X value. Does anyone have any idea how to try to improve this code?

I've searched for several ideas on the internet, but I haven't found anything that would help me in this specific case.

date1 = ''
date2 = ''
name = ''

query = ''

if date1 and date2 and name:
    query = 'query 1'
elif date1 and date2:
    query = 'query 2'
elif date1 and name:
    query = 'query 3'
else:
    query = 'query default'

CodePudding user response:

You could eliminate the need for the else by initializing query with the default value.

CodePudding user response:

You can try mapping your input values to queries

# map (date1, date2, name) => query
query_map = {
    (date1, None, None): query1,
    (None, date2, None): query2,
    (date1, None, name): query3,
}

query = query_map.get((input_date1, input_date2, input_name), "default_query")

CodePudding user response:

i think it is overall fine atleast in my opinion. You could use pythons all() function to check if all elements are true. Maybe you could chain the elements differently but still i think its fine. Since Python 3.10 you could use match aswell.

if all(date1,date2):
# do something

CodePudding user response:

Using a generator and next:

query = next(v for k,v in [(date1 and date2 and name, 'query 1'),
                           (date1 and date2, 'query 2'),
                           (date1 and name, 'query 3'),
                           (True, 'query default')]
               if k)
  • Related