Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
backtrace
traceback

What is stack trace in Python?

Ammar Ahmad Farid

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Definition

When a code throws an exception, Python prints a stack trace. A stack trace is also known as stack traceback, traceback, or backtrace. The Python stack trace contains a lot of information that can assist in determining the cause of a problem. To become better Python programmers, we must first understand what information a Python stack trace gives.

To put it another way, a stack trace shows all the calls made before the function that threw an error. The most relevant information is always written on the final line of a stack trace because this is where the error is reported. All of the information in the thrown error is made up of function calls that can help us to locate and fix the error quickly.

Example

The function calls made in our code just before the error are recorded in a stack trace report. When our application throws an exception, the stack trace is printed.

Let’s check the example below:

def printName(name, age):
print("Hi, ",name)
print("Are you",ag, " years old ?")
printName("Marry",20)
Stack trace as output

Explanation

The above stack trace contains a lot of information about what went wrong. It tells us about the type of error that has occured: NameError. This exception tells us we’ve referenced a variable that doesn’t exist. Here, ag is not defined. This exception generally tells us that a variable, function, or class has been referenced incorrectly.

RELATED TAGS

python
backtrace
traceback

CONTRIBUTOR

Ammar Ahmad Farid
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring