OwenHoward OwenHoward - 12 days ago 6
Python Question

For this recursive code why does Python 2.7 not give a stack overflow error but 3.5 does?

Earlier today I read about this strange case in

Python
,
Java
&
JS
:

try:
return True
finally:
return False


Which returns
False
.

So, I decided to toy around with it:

def caseThree():
try:
caseThree()
except:
print("Error")
caseThree()
finally:
return False
print(caseThree())


In Python
2.7
this returns:

Error
False


However, in Python
3.5
:

Error
Fatal Python error: Cannot recover from stack overflow.

Current thread 0x000025ec (most recent call first):
File "`<stdin>`", line 3 in caseThree


the last line is repeated until you eventually get:
...


Can anyone explain why
2.7
's code doesn't result in a stack overflow, while
3.5
does?

Answer

It seems that the error you're encountering is actually expected, as it is explicitly tested for in Lib/test/test_sys.py function test_recursionlimit_fatalerror.

Now, without criticizing your colorful experiments, this is also the cause of a bug that causes a segfault (sometimes, see issue); there has already been one report of this to the Python bug tracker as issue 28179.

Keep an eye on that thread if you're curious as to what is causing this.