args = [-1]
while args:
    n = len(args)
args[-1] += 1
if args[-1] >= B[n - 1]:
    args.pop()
elif n == len(B):
    dostuff(*args)
else:
    args.append(F[n](args[-1]) - 1)
assert expected == stefan
Using itertools for arbitrary number of nested loops of different ranges with dependencies?