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?
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.
We can create an infinite loop using while statement. If the condition of while loop is always True , we get an infinite loop.
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.
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++) { ... }
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With