Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Python handle infinite recursion?

So when toying with Python, I noticed that there is basically no limit on the program's stack size (kept performing power operations on a number, the precision stayed perfect even after getting to like thousands of digits). This makes me wonder: what if I accidentally got into an infinite recursive loop in Python? Would the compiler notice and throw a stack overflow error? Or would the program just crash? Would my CPU combust? This isn't something that I'd be eager to test myself, honestly.

like image 448
Coffee Maker Avatar asked Sep 21 '25 02:09

Coffee Maker


1 Answers

No modern computer is going to combust due to user code, I promise. Try it for yourself:

def recurseInfinitely( n ):
    recurseInfinitely(n+1)

recurseInfinitely(0)

Running this program promptly yields the output:

  [...]
    recurseInfinitely(n+1)
  File "so.py", line 2, in recurseInfinitely
    recurseInfinitely(n+1)
  File "so.py", line 2, in recurseInfinitely
    recurseInfinitely(n+1)
RuntimeError: maximum recursion depth exceeded   

You can catch the error and check the value of n:

def recurseInfinitely( n ):   
    try:
        recurseInfinitely(n+1)
    except RuntimeError:
        print "We got to level %s before hitting the recursion limit."%n

And get:

We got to level 997 before hitting the recursion limit.

like image 178
Russell Borogove Avatar answered Sep 22 '25 17:09

Russell Borogove