Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this Python script create an infinite loop? (recursion)

Why/how does this create a seemingly infinite loop? Incorrectly, I assumed this would cause some form of a stack overflow type error.

i = 0

def foo () :
    global i

    i += 1
    try :
        foo()
    except RuntimeError :
        # This call recursively goes off toward infinity, apparently.
        foo()

foo()

print i
like image 828
rectangletangle Avatar asked Jun 27 '12 08:06

rectangletangle


1 Answers

The RuntimeError exception will be raised if the recursion limit is exceeded.

Since you're catching this exception, your machine is going to continue on, but you're only adding to a single global int value, which doesn't use much memory.

You can set the recursion limit with sys.setrecursionlimit(). The current limit can be found with sys.getrecursionlimit().

>>> import sys
>>> sys.setrecursionlimit(100)
>>>
>>> def foo(i):
...     i += 1
...     foo(i)
...
>>> foo(1)
Traceback (most recent call last):
  ...
  File "<stdin>", line 3, in foo
RuntimeError: maximum recursion depth exceeded
>>>

If you want to run out of memory try consuming more of it.

>>> def foo(l):
...     l = l * 100
...     foo(l)
...
>>> foo(["hello"])
Traceback (most recent call last):
  ...
  File "<stdin>", line 2, in foo
MemoryError
>>>
like image 132
monkut Avatar answered Sep 20 '22 11:09

monkut