SRR
SRR

Reputation: 1748

How to check that many functions succeeded? - Python

I have a function that I want to run only if 6 prior functions have returned True or successful. Currently I do that with the following code:

PATHS_GOOD = COUNT_EQUAL = ALL_FILES_PAIRED = VAL_PATHS_GOOD = VAL_COUNT_EQUAL = VAL_ALL_FILES_PAIRED = ALL_CLEAR = False

# Execute functions that change the state of COUNT_EQUAL etc
ALL_CLEAR = PATHS_GOOD and COUNT_EQUAL and ALL_FILES_PAIRED and VAL_PATHS_GOOD and VAL_COUNT_EQUAL and VAL_ALL_FILES_PAIRED

if ALL_CLEAR: 
    #Execute

Can I just use shorter variable names? Sure but then no one else will know what that variable is responsible for. This approach won't scale well if I have to keep adding more checks. So how can I possibly make this less verbose and scalable ?

Upvotes: 1

Views: 211

Answers (1)

ruohola
ruohola

Reputation: 24058

Generally it's not a good idea to pass information around by mutating global variables. Instead you could make the functions return a bool based on their success and then use all() to check that they all returned True:

if all((
    paths_good(),
    count_equal(),
    all_files_paired(),
    val_paths_good(),
    val_count_equal(),
    val_all_files_paired(),
)):
    # execute

Or alternatively just use and between each function call:

if (
    paths_good() 
    and count_equal() 
    and all_files_paired() 
    and val_paths_good() 
    and val_count_equal() 
    and val_all_files_paired()
):
    # execute

Upvotes: 1

Related Questions