About me
About me

Reputation: 31

Reduce number of conditions

I have this long list of conditions inside a function:

if x == "a":
    return function_a()
elif "b" in x:
    return function_b()
elif x == "c string":
    return function_c()
elif x == "d string":
    return function_d()
else:
    function_e()

How can I simplify this so that I can reduce the cognitive complexity of my function?

Upvotes: 0

Views: 146

Answers (2)

About me
About me

Reputation: 31

This is my take on this:

def function_a():
  return 'a'

def function_b():
  return 'b'

def function_c():
  return 'c'

def function_d():
  return 'd'

def function_e():
  print('e')

x = 'b'

L = {
  'a': function_a(),
  'c string': function_c(),
  'd string': function_d()
}

def reduced():
  try:
    L[x]()
  except KeyError:
    if 'b' in x:
      return function_b()
    else:
      function_e()

print(reduced())

If anyone could improve it?

Upvotes: 0

Priyanka Rao
Priyanka Rao

Reputation: 208

You could do like this:

def function_a():
    print("First function")
    
def function_b():
    print("Second function")
    
x = 'b'
fns = {'a': function_a, 'b': function_b}
fns[x]()

Python doesn't have a switch statement so a common alternative is using a dictionary to "choose" which option to take. In this example, the values that you expect a,b,c,d... are the keys in a dictionary and the corresponding function is the value of that key.

To execute the correct function, you just need to access the dictionary with fns[x] which returns a function, and then call the function with the () brackets.

Upvotes: 1

Related Questions