Here is a very short version:
Create a file with the name break_out_nested.py
import itertools
import sys
it = sys.modules[__name__] # this allows us to share variables with break_out_nested.py when we import it
def bol(*args):
condi = args[-1] # the condition function
i = args[:-1] # all iterables
for p in itertools.product(*i): # itertools.product creates the nested loop
if condi(): # if the condition is True, we return
return
yield p # if not, we yield the result
Now you need only a few lines to break out of nested loops (data from Rafiq's example)
from break_out_nested import it, bol # import what we have just created
# you need to create new variables as attributes of it,
# because break_out_nested has only access to these variables
it.i, it.j, it.k = 1, 1, 1
# the break condition
def cond(): return it.i % 3 == 0 and it.j % 3 == 0 and it.k % 3 == 0
# The condition will be checked in each loop
for it.i, it.j, it.k in bol(range(1, 6, 1), range(1, 11, 2, ), range(1, 21, 4), cond):
print(it.i, it.j, it.k)
More examples:
def cond(): return it.i + it.j + it.k == 777
it.i, it.j, it.k = 0, 0, 0
for it.i, it.j, it.k in bol(range(100), range(1000), range(10000), cond):
print(it.i, it.j, it.k)
def cond(): return it.i + it.j + it.k >= 100000
it.i, it.j, it.k = 0, 0, 0
# you dont have to use it.i, it.j, it.k as the loop variables, you can
# use anything you want, but you have to update the variables somewhere
for i, j, k in bol(range(100), range(1000), range(10000), cond):
it.i, it.j, it.k = i * 10, j * 100, k * 100
print(it.i, it.j, it.k)
try
except
block and escape by raising an exception. It's the most readable approach IMO – Windflower