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

Why / how does this create an infinitely closed loop? Wrong, I assumed that this would result in a type 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 
+6
source share
2 answers

If you change the code to

 i = 0 def foo (): global i i += 1 print i try : foo() except RuntimeError : # This call recursively goes off toward infinity, apparently. foo() finally: i -= 1 print i foo() 

You will notice that the output fluctuates below 999 (1000 is Python's default recursion limit). This means that when the limit ( RuntimeError ) is RuntimeError last call to foo() completed, and the other to immediately replace it.

If you raise KeyboardInterrupt , you will see how the entire track terminates immediately.


UPDATE

Interestingly, the second call to foo() no longer protected by a try ... except block. Therefore, the application will eventually terminate. This will become apparant if you set the recursion limit to a smaller number, for example. output for sys.setrecursionlimit(3) :

 $ python test.py 1 2 1 2 1 0 Traceback (most recent call last): File "test.py", line 19, in <module> foo() File "test.py", line 14, in foo foo() File "test.py", line 14, in foo foo() RuntimeError 
+4
source

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

Since you catch this exception, your machine will continue to run, but you will add only one global int value that does not consume much memory.

You can set the recursion limit with sys.setrecursionlimit() . The current limit can be found using 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 using it more.

 >>> def foo(l): ...   l = l * 100 ...   foo(l) ... >>> foo(["hello"]) Traceback (most recent call last): ... File "<stdin>", line 2, in foo MemoryError >>> 
+6
source

Source: https://habr.com/ru/post/919108/


All Articles