Riki Lyng Riki Lyng - 1 year ago 134
Python Question

Python: process flow avoiding nested IF statements

I have a process (class) that I split into several steps (methods). each step can only be invoked if the previous one was successful. I created a method run() that runs the process by checking each step before invoking the next one:

def run(self):
status = False
if step_1():
if step_2():
if step_3():
etc... [several nested IFs]
status = True
self.logger.error('Error in step 3')
self.logger.error('Error in step 2')
self.logger.error('Error in step 1')
return status

Is there a more elegant way (a design pattern?) to avoid these nested IF statements?

Thanks a lot,

Answer Source

You would place your steps in a list:

my_plan = (step1, step2, step3, ..., stepN)

And then execute them in a loop:

for step in my_plan:
   if not step():
      print 'Error in %s' % step.__name__
      status = False
    status = True
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download