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?

Mazdak
  • 105,000
  • 18
  • 159
  • 188
Hubro
  • 56,214
  • 69
  • 228
  • 381
  • People go to hell for demon loops, not for daemons ;-) In Python, you will just get an exception, "RuntimeError: maximum recursion depth exceeded". – Raymond Hettinger Nov 02 '11 at 04:10

6 Answers6

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.

Jeremy
  • 1
  • 85
  • 340
  • 366
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
agf
  • 171,228
  • 44
  • 289
  • 238
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.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • Why would the interpreter raise an error if you never return? This is either unclear or wrong. – agf Nov 02 '11 at 03:34
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.

AusCBloke
  • 18,014
  • 6
  • 40
  • 44
0

Probably not a good idea....

def forever(): forever()

forever()

RuntimeError: maximum recursion depth exceeded

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

Tony
  • 414
  • 3
  • 6
0
(define forever (lambda () (forever)))

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