Rodrigo Ney Rodrigo Ney - 2 months ago 6
Python Question

Best Design Pattern to execute steps in python

I have to execute multiple actions sequentially in an order dependant manner.

StepOne(arg1, arg2).execute()
StepTwo(arg1, arg2).execute()
StepThree(arg1, arg2).execute()
StepFour(arg1, arg2).execute()
StepFive(arg1, arg2).execute()


They all inherit from the same
Step
class and receive the same 2 args.

class Step:
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2

def execute(self):
raise NotImplementedError('This is an "abstract" method!')


What's the most idiomatic way to execute these actions in order? Is there a design pattern that would apply here?

Answer

You could create a list of the step classes, then instantiate and call them in a loop.

step_classes = [StepOne, StepTwo, StepThree, ...]

for c in step_classes:
    c(arg1, arg2).execute()
Comments