0

I have four functions and each one returns a list as a result. I want whichever of these functions that I call sequentially brings a list, not to look at the others. Thank you for your help.

def main(self):
    print(self.df_list)
    
    funcs = [(Calculate.free_two_kdv(self.df_list)),(Calculate.free_kdv(self.df_list)),(Calculate.zero_kdv(Calculate.find_largest_duplicated_value,self.df_list)),(Calculate.zero_with_other_kdv(Calculate.find_largest_duplicated_value,self.df_list))]
    for func in funcs:
        try:
            
            func()
            
        except ValueError:
            break

In short, I don't want it to go to other functions at all, whichever brings results.

1
  • 1
    You are not calling them inside the loop, you call them when you define the list. There is no enough information to suggest how you can refactor the code. Commented Dec 18, 2021 at 20:01

2 Answers 2

1

You are calling your functions immediately and storing the result in the list. Define a new function which makes the desired function call.

def main(self):
    print(self.df_list)
    
    funcs = [lambda: Calculate.free_two_kdv(self.df_list),
             lambda: Calculate.free_kdv(self.df_list),
             lambda: Calculate.zero_kdv(Calculate.find_largest_duplicated_value, self.df_list),
             lambda: Calculate.zero_with_other_kdv(Calculate.find_largest_duplicated_value, self.df_list)
    ]

    for func in funcs:
        try:
            return func()
        except ValueError:
            pass

It's not clear if you want Calculate.find_largest_duplciated_value as an argument to the first function, or if you want function composition (i.e., f(g, x) vs f(g(x)). If you want composition, it's

    funcs = [lambda: Calculate.free_two_kdv(self.df_list),
             lambda: Calculate.free_kdv(self.df_list),
             lambda: Calculate.zero_kdv(Calculate.find_largest_duplicated_value(self.df_list)),
             lambda: Calculate.zero_with_other_kdv(Calculate.find_largest_duplicated_value(self.df_list))
    ]
Sign up to request clarification or add additional context in comments.

2 Comments

That's not what's written the original (though that might be what's intended).
You might be right, though; the original looks odd. I'm going to mention that (plus, what I have now isn't ideal).
0

Assuming that the func in funcs return either a list or None:

for func in funcs:
    if func(): break
for func in funcs:
    flist = func()
    if flist: break

The second receives the return value from the function for further work. try..except in this case has a greater performance cost than a straightforward boolean condition.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.