Iam creating a code in Python in which I have defined in total of 8 functions. These functions are called and should be executed one after another in series. If one fails, other function will not work. My question is how to call the functions only if the previous function is executed correctly. I can do it using if loop while calling. But is there any other effective way which I can use?
def func():
do something
return
def func2()
do something
return
def func3()
do something
return
def main():
func()
if func():
func2()
if __name__ == '__main__':
main()
Is there any efficient way other than this?
CodePudding user response:
If a function does not execute correctly (i.e. it throws an Exception), the main program thread will stop executing automatically, so you don't need to add some custom logic for handling these cases.
NOTE: Be careful with the return indent (it's outside the functions)
CodePudding user response:
Assuming the functions return a boolean that indicates whether they're successful, you can use the short-circuiting of and
:
def main():
func() and func2() and func3() ...
With a bunch, you could use a loop that checks the return value of each call.
def main():
for f in [func, func2, func3, ...]:
if not f():
break
or more simply:
def main():
all(f() for f in [func, func2, func3, ...])
See Does Python's `all` function use short circuit evaluation? for the explanation of why this works.