I am very new with Python, I do still not understand what stack traceback in python is? Could you explain it for me? Thanks for your help very much!
The stack traceback displays the state of the call stack at a certain point in the running of a program. In practice, you'll usually encounter these when an error occurs in your program.
The call stack is a stack (or list) of stack frames. Each stack frame corresponds to the call of a subprocess (in Python, a function or [list]-comprehension). A stack is a data structure that can contain many elements, which are removed in last-in-first-out (LIFO) fashion.
This can be hard to understand in abstract, but with an example it's fairly simple.
Example:
If you have the program:
def func1():
func2()
def func2():
print("func2")
And you call the function func1
, the the call stack will initially contain a call frame for func1
. Then func1
calls func2
, which adds a call frame to the stack. When func2
exits, the corresponding call frame is removed from the stack, so now we're back in func1
. When func1
exits, its call frame is also removed and now the stack is empty again.
So we would have the following stack traces:
[empty] --> func1 --> func1 --> func1 --> [empty]
func2
Stack traces are useful in debugging, especially in more complex examples as they show where the program was when it encountered an error. For example, if we modify func2
so that it looks like:
def func2():
1 / 0
We would get a ZeroDivisionError
with the following stack traceback:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in func1
File "<stdin>", line 2, in func2
ZeroDivisionError: division by zero
So we can see the error occurred in line 2 of func2
(which was called on line 2 of func1
).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.