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

6

9

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?

Floats answered 2/11, 2011 at 3:29 Comment(1)
People go to hell for demon loops, not for daemons ;-) In Python, you will just get an exception, "RuntimeError: maximum recursion depth exceeded".Signorino
K
17

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.

Kutchins answered 2/11, 2011 at 3:31 Comment(0)
S
5

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
Supporting answered 2/11, 2011 at 3:33 Comment(0)
P
1

The C version of the Python interpreter (which is probably what you're using) will raise an error eventually if you never return from daemonLoop. I'm not sure about other versions.

Proprietor answered 2/11, 2011 at 3:31 Comment(1)
Why would the interpreter raise an error if you never return? This is either unclear or wrong.Supporting
P
1

I don't know why you'd think about doing something like that when you could simply have an infinite while loop. Anyway for your question about 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, hell it is.

Provenance answered 2/11, 2011 at 3:34 Comment(0)
A
0

Probably not a good idea....

def forever(): forever()

forever()

RuntimeError: maximum recursion depth exceeded

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

Augment answered 2/11, 2011 at 3:33 Comment(0)
R
0
(define forever (lambda () (forever)))

This kind of recursion is what Lisp dialects like Scheme are made for!

Rothschild answered 2/11, 2011 at 5:57 Comment(1)
Yeah, but that wasn't the question.Thermos

© 2022 - 2024 — McMap. All rights reserved.