dimanche 24 avril 2016

Pattern for executing common code when using continue inside a Python loop

validate_input():
    while not_valid:
        attempt += 1
        inpt = prompt_and_get_input()

        if validate_check1(inpt) is False:
            # common code for invalid_state
            continue

        if validate_check2(inpt) is False:
            # common code for invalid_state
            continue

        # ... repeat ....

        not_valid = False # Valid state

I would like to factor out the duplicated common code that and place it in only a single location in the loop. I understand that I could put it inside of a function/method, but there would still be duplicated calls.

I would like to do something like:

    validate_input():
    while not_valid:
        attempt += 1
        inpt = prompt_and_get_input()

        if validate_check1(inpt) is False:
            continue

        if validate_check2(inpt) is False:
            continue

        # ... repeat ....

        not_valid = False # Valid state
    else:
        # We get here anytime a validate_check() fails via continue
        # common vode for _invalid_state

I understand that the else clause for a loop will only execute if the loop executes normally (vs. via break). I want sort of the opposite functionality where the xxx clause only gets executed in the event that the loop didn't iterate naturally (i.e. a continue statement)

I know there is no built-in feature for this functionality, but is there a better pattern for what I would like to do? This pattern has come up several times in the project I'm working on.

Aucun commentaire:

Enregistrer un commentaire