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
If you change the code to
You’ll observe that the output oscillates short below 999 (1000 being Python’s default recursion limit). That means, when the limit is hit (
RuntimeError) that last call offoo()is terminated, and another one is set off to replace it immediately.If you raise a
KeyboardInterruptyou’ll observe how the entire trace is being terminated at once.UPDATE
Interestingly the second call of
foo()is not protected by thetry ... except-block anymore. Therefore the application will in fact terminate eventually. This becomes apparant if you set the recursion limit to a smaller number, e.g. the output forsys.setrecursionlimit(3):