Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can python throw a "stack overflow" error?

Can python have a stack overflow error?
Recently I was just letting my mind wander when I came across the question: "can python get the stack overflow error? Does anyone have any answers?

I searched for the answer but only found java answers. I have used java but its just not my question:

  1. What is a StackOverflowError?
  2. https://rollbar.com/blog/how-to-fix-java-lang-stackoverflowerror-in-java/

My Reasoning
I initially thought no because python just... works most of the time (like passing an int for a string). It also doesn't have stacks (to my knowledge). But I wasn't sure. Here I am.

like image 398
Evergreen Avatar asked Jan 25 '23 05:01

Evergreen


2 Answers

Sure it can

the following code will cause a seg fault:

import sys
sys.setrecursionlimit(10_000_000)

def foo():
    foo()

On Mac OS, this throws:

Segmentation fault: 11

Which is caused by a stack overflow.

like image 122
juanpa.arrivillaga Avatar answered Jan 26 '23 19:01

juanpa.arrivillaga


You can, if your recursion limit is too high:

def foo():
    return foo()


>>> foo()

Result:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  .......
  File "<stdin>", line 2, in foo
RuntimeError: maximum recursion depth exceeded
>>> 

The default recursion limit is 10**3 (verifiable via sys.getrecursionlimit), but you can change it using sys.setrecursionlimit:

import sys
sys.setrecursionlimit(10**8)

def foo():
    foo()

but doing so could be dangerous -- the standard limit is a little conservative, but Python stackframes can be quite big.

like image 37
krmogi Avatar answered Jan 26 '23 19:01

krmogi