Search code examples
pythonloopscontrol-flow

Pythonic way to stop file validation


I am writing a script to validate csv files. I have several functions that do things like checking if a certain field is below some threshold, or check if there are any NaN values.

These functions return(True) if the checks are passed, return(False) otherwise.

I am trying to figure out the correct/pythonic way to stop processing once one of these checks fails & returns False.

I tried while True, but this only evaluates the last value returned in the loop. Any help is appreciated!

#I have functions that validate certain things in a csv file
#those functions return(True) if they pass the test, return(False) otherwise.

#I want to be able to call these functions and have the file stop 
#processing once a False is returned.

def function1():
    return(True)
def function2():
    return(True)
def function3():
    return(False)
def function4():
    return(True)

#works, but not pythonic.
checkpoint1 = function1()
if checkpoint1 == True:
    checkpoint2 = function2()
    if checkpoint2 == True:
            checkpoint3 = function3()
            if checkpoint3 == True:
                checkpoint4 = function4()
                if checkpoint4 == True:
                    print("all checkpoints passed")
                else:
                    print("Fail 4")
            else:
                print("Fail 3")
    else:
        print("Fail 2")
else:
    print("Fail 1")

Solution

  • Combine the functions into a single list, then iterate over that list to call each, breaking early if one fails.

    for i, f in enumerate([function1, function2, function3, function4], start=1):
        if not f():
            print(f"Fail {i}")
            break
    else:
        print("all checkpoints passed")
    

    If you didn't want the output, you could simply use all:

    if all(f() for f in [function1, function2, function3, function4]):
        print("all checkpoints passed")
    else:
        print("One checkpoint failed")