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

This question is more about curiosity than utility. If I write a function that should run forever, such as a daemon, how would Python deal with it if I called the function again from the end of the function?

def daemonLoop(): # Declare locals # Do stuff daemonLoop() 

I am sure that doing this in C will lead to a stack overflow, but given the level of abstraction from C to Python. I assume that the material is handled differently.

Could I go to hell for this?

+8
c python recursion infinite-loop
source share
6 answers

Almost all Python interpreters that cause a stack overflow, as it would be in C. A higher-level function that would allow this to be done is called Call Optimization or Tail Recursion Elimination, and the friendly Python dictator opposes adding this to the language .

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

+16
source share

The maximum recursion depth can be obtained using sys.getrecursionlimit() and set using sys.setrecursionlimit() .

Could I go to hell for this?

Yes. CPython has no exception for tail recursion / optimization of the last call.

 def recurse(): recurse() recurse() 

Mistake:

   # 1000 or so lines of this:
   File "", line 2, in recurse
 RuntimeError: maximum recursion depth exceeded
+5
source share

The C version of the Python interpreter (which is probably what you are using) will ultimately result in an error if you never return with daemonLoop . I am not sure about other versions.

+1
source share

I don’t know why you are thinking of doing something like this when you could just have an infinite while . In any case, the question of whether it will work:

 ... File "test.py", line 7, in daemonLoop daemonLoop() File "test.py", line 7, in daemonLoop daemonLoop() RuntimeError: maximum recursion depth exceeded 

So yeah, damn it.

+1
source share

Probably not a good idea ....

 def forever(): forever() forever() 

RuntimeError: maximum recursion depth exceeded

http://paulbarry.com/articles/2009/09/02/infinite-recursion

0
source share
 (define forever (lambda () (forever))) 

Such recursion is what dialects like Lisp do, such as Scheme!

0
source share

All Articles