Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a sin to use infinite recursion for infinite loops in Python?

This question is more about curiosity than utility. If I'm writing a function that's supposed to run for ever, for instance a daemon, how would Python handle it if I called the function again from the end of the function?

def daemonLoop():

    # Declare locals

    # Do stuff

    daemonLoop()

I'm fairly sure that doing this in C would result in a stack overflow, but given the level of abstraction from C to Python I'm guessing stuff is handled differently.

Would I go to hell for this?

like image 766
Hubro Avatar asked Nov 02 '11 03:11

Hubro


People also ask

Can recursion causes infinite loop?

Iteration and recursion can occur infinitely: An infinite loop occurs with iteration if the loop-continuation test never becomes false; infinite recursion occurs if the recursion step does not reduce the problem in a manner that converges on the base case.

Can you have an infinite for loop in Python?

We can create an infinite loop using while statement. If the condition of while loop is always True , we get an infinite loop.

What is often the cause of infinite recursion?

Infinite Recursion occurs when the recursion does not terminate after a finite number of recursive calls. As the base condition is never met, the recursion carries on infinitely.

Is it possible to make an infinite for loop?

A for loop is only another syntax for a while loop. Everything which is possible with one of them is also possible with the other one. Any for loop where the termination condition can never be met will be infinite: for($i = 0; $i > -1; $i++) { ... }


2 Answers

In almost all Python interpreters that will cause a stack overflow, as it would in C. The higher-level feature that would permit this is called Tail Call Optimization or Tail Recursion Elimination, and the benevolent dictator of Python opposes adding this to the language.

This style is considered to be non-idiomatic for Python, and a simple while True: loop is preferred.

like image 193
Jeremy Avatar answered Sep 23 '22 14:09

Jeremy


The maximum recursion depth can be retrieved with sys.getrecursionlimit() and set with sys.setrecursionlimit().

Would I go to hell for this?

Yes. CPython has no Tail Recursion Elimination / Last Call Optimization.

def recurse():
    recurse()

recurse()

Error:

  # 1000 or so lines of this:
  File "", line 2, in recurse
RuntimeError: maximum recursion depth exceeded
like image 21
agf Avatar answered Sep 22 '22 14:09

agf