Home > Software design >  Is there a way to have a function invoke 'continue' affecting a loop in its caller?
Is there a way to have a function invoke 'continue' affecting a loop in its caller?

Time:04-24

I am trying to refactor a code that consists of nested loops. For a similar repetitive code snippet, I am trying to write a function which consists of a 'continue' within. The loop is very long and I just want to include the if statement in the function.

def calc_indexes_for_rand_switch_on(self, switch_on, rand_time, max_free_spot, rand_window):
    if np.any(self.daily_use[switch_on:rand_window[1]] != 0.001):  # control to check if there are any other switch on times after the current one
        next_switch = [switch_on   k[0] for k in np.where(self.daily_use[switch_on:] != 0.001)]  # identifies the position of next switch on time and sets it as a limit for the duration of the current switch on
        if (next_switch[0] - switch_on) >= self.func_cycle and max_free_spot >= self.func_cycle:
            upper_limit = min((next_switch[0] - switch_on), min(rand_time, rand_window[1] - switch_on))
        elif (next_switch[0] - switch_on) < self.func_cycle and max_free_spot >= self.func_cycle:  # if next switch_on event does not allow for a minimum functioning cycle without overlapping, but there are other larger free spots, the cycle tries again from the beginning
            continue
        else:
            upper_limit = next_switch[0] - switch_on  # if there are no other options to reach the total time of use, empty spaces are filled without minimum cycle restrictions until reaching the limit
    else:
        upper_limit = min(rand_time, rand_window[1] - switch_on)  # if there are no other switch-on events after the current one, the upper duration limit is set this way
    return np.arange(switch_on, switch_on   (int(random.uniform(self.func_cycle, upper_limit)))) if upper_limit >= self.func_cycle \
        else np.arange(switch_on, switch_on   upper_limit)

This is the function I am trying to write. The if statement is a part of bigger while loop in the main code. But, here this gives an error since there is no loop. How can I solve this?

CodePudding user response:

You can return a sentinel value here, e.g. None and handle this in the caller.

So in your function:

    elif (next_switch[0] - switch_on) < self.func_cycle and max_free_spot >= self.func_cycle:  # if next switch_on event does not allow for a minimum functioning cycle without overlapping, but there are other larger free spots, the cycle tries again from the beginning
        return None

And use it like:

while some_condition():
    # do some stuff
    ...
    result = calc_indexes_for_rand_switch_on(switch_on, rand_time, max_free_spot, rand_window)
    if result is None:
        continue
    ...
    # do stuff with result
  • Related