pythoncrecursioninfinite-loopfunction-calls

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?


Solution

  • 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.