It is necessary to interrupt the loop while inside the function, is it possible? Such code:

def func(): if True: break while True: func() 

Naturally does not work. Can be replaced by:

 def func(): if True: return True while True: if func(): break 

but this adds an "extra" check to the loop, which is undesirable.

You can refuse to use the function, and just copy the code with the break, but this will turn everything into an unreadable mess. Are there any other options?


Added by:

very roughly the code looks like this: (it is, of course, more, but I don’t know what else could be important)

 def func(p1,p2,p3): answer = api(p1,p2,p3) if answer['ответ'] == не_устраивающие_нас_значение: break while True: #что-то считаем if что-то-там: #еще что-то считаем if еще-что-то: func(p1,p2,p3) 
  • can, but how, depends on your code (the solution for one case may not be suitable for another). Give a more realistic (minimal) example - jfs
  • @jfs Thanks for the reply. I didn’t quite understand what you want to see, in my case everything looks like this, now I’ll add to the question. - AAA
  • @jfs Done ......... - AAA

3 answers 3

In your example, return from exit / exit exit function works:

 if "еще-что-то" and not keep_doing_it(p1,p2,p3): break 

where the function keep_doing_it(*p) returns False if the loop should be stopped.

In general, if due to an error a cycle must be stopped, then an exception can be thrown, for example, raise TimeoutError("X takes too long") .

If you want to finish the work at all, you can call sys.exit("reason") .

It depends on the function where exit() placed, it is possible to combine: one function throws out a suitable error, and the code above the stack can already exit() when processing an error if the error is uncorrectable.

In some cases, when the function is closely related to the cycle and the cycle itself inside the generator, you can raise StopIteration throw it away, as the next() function does. Although it is recommended to catch StopIteration in the new code and use an explicit return in the generator . Therefore, it may be easier to simply return the Boolean status.

If the generator is passed as an explicit object, then methods such as the .throw() , .close() method can be called to stop the generator from the cooperating function prematurely. But such things rarely need to be done. They are useful to enable higher-level functionality, and not for direct use.

  • 1. A beautiful and interesting solution, although it adds a "superfluous" logical multiplication to the cycle, which is probably better than an extra if, but still. 2. About exceptions, I do not know, the same question: using try except takes or does not take additional processor time in the loop? 3. exit () fits perfectly, without unnecessary burden, but of course, the option is not for every occasion. About generators is not my case, but I am sure that users from Google will be very useful :) - AAA

You can throw an exception, and catch it in the upper function. It’s not ideologically very good to do so, if the situation “didn’t like the meaning” is quite adequate - exceptions are nevertheless meant for exceptional situations in which it is necessary to interrupt the execution of the code immediately, as further actions are meaningless.

Examples of situations in which I would use an exception: the server is unavailable, authorization failed, the user was banned. In which I would not: the calculation ended with the result true (and we were looking for just the first true ).

  • Using try except takes or not additional processor time in the loop? If not, then this is quite a suitable option. - AAA
  • @AAA as far as I know, there is almost no time to try / catch, but catching an exception is relatively long. - yeputons
  • That is, compared with a simple if construction - the advantage does not give much? Anyway, thanks for the reply :) - AAA
 def func(): print("Call func") setattr(func2, "flag", 0) # если нужно прервать цикл def func2(): func2.flag = 1 try: while True: assert func2.flag func() except AssertionError: # ваш дальнейший код print("Выход из цикла") func2() 

And catch AssertionError!

  • Using try except takes or not additional processor time in the loop? And assert? - AAA
  • Would you ask how much time it takes to call a function !? Are you aware that calling a function is a very time consuming operation? - Xyanight
  • And I thought somewhere to ask this. It was assumed, but was not in the know. So thanks for that too :) - AAA