Search code examples
pythonfunctiongeneratorreusability

How to re-use the same function but call it from different locations in python in same test script


I've a test case in which I've to "End the process" from different screens on a device and I've a function to emulate the different screens. After EndProcess(), device returns to screen1(). Any optimistic way to do this in Python? Can I use a generator here?

Currently, my code is:

while 1:
    screen1()
    EndProcess()
    screen1()
    screen2()
    EndProcess()
    screen1()
    screen2()
    screen3()
    EndProcess()

Solution

  • You'll be repeating yourself so many times when the number of screens become relatively large. Instead, you can put the screens in a list and call them using a for loop:

    screens = [screen1, screen2, screen3]
    
    while True:
       for x in range(len(screens)):
          for i in range(x+1):
             screens[i]()
          EndProcess()
    

    Use xrange in place of range in Python 2.