7/36
Part 2 of 8 · RecursionLearn and do
Recursion is a stack you don't see
Here's a small program that fails three calls deep:
import traceback
def parse(text):
print([frame.name for frame in traceback.extract_stack()])
return int(text)
def load(lines):
return [parse(line) for line in lines]
def main():
return load(["1", "2", "x"])
main()
['<module>', 'main', 'load', 'parse']
['<module>', 'main', 'load', 'parse']
['<module>', 'main', 'load', 'parse']
Traceback (most recent call last):
File "app.py", line 17, in <module>
main()
File "app.py", line 14, in main
return load(["1", "2", "x"])
^^^^^^^^^^^^^^^^^^^^^
File "app.py", line 10, in load
return [parse(line) for line in lines]
^^^^^^^^^^^
File "app.py", line 6, in parse
return int(text)
^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'x'
That's Python 3.12's output, with the folder cut from each path.
Every call pushes a frame, and a traceback prints the frames outermost first
main calls load, which calls parse once per line. Not counting <module>, at most how many frames are on the call stack?
Pick an answer above to see the rest