-2

I am using several smallish custom defs that get called in an iterator. In the instance one of the defs catches an exception I want it to quit that definition and keep the script running. Main flow is as follows:

for TIME in QueuedTimes:
    def1(DATE, TIME)
    def2(DATE, TIME)
    def3(DATE, TIME)

Assuming all is well in the upstream def1(), I would like the logic of def2() as follows

def def2(DATE, TIME):
    <beginstuff>
    while True:
        if exists(fileloaderror):
            print 'found error'
            break
        else:
            print 'pass'
            break
     <end stuff>

This while True works, but only to evaluate the conditions. I want the break to jump to the end of def2() and proceed to def3() and skip all the rest of the <end stuff> that would be broken by the exception I hope to catch. Is there a more trusted way of doing this?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
maphilli14
  • 19
  • 5

2 Answers2

2

If you need to exit a function early, use return:

def def2(DATE, TIME):
    # stuff at the start
    while True:
        if exists(fileloaderror):
            print 'found error'
            break
        else:
            print 'pass'
            return
     # stuff at the end

This will break out of the loop and skip the stuff at the end.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

Unless I miss something, the while True is useless as it will exit anyway as soon as it is entered because one of the if ... else ... will break or return the loop.

Why not do:

def def2(DATE, TIME):
    # stuff at the start
    if not exists(fileloaderror):
        print 'pass'
        return
    print 'found error'
    # stuff at the end
Ptah
  • 571
  • 1
  • 5
  • 8