SoFunction
Updated on 2024-11-16

An introduction to the interpretation of traceback on python errors

When writing Python code, when there is an error in the code, the Traceback error message will be printed on the output, and many beginners will be in a state of confusion when they see a bunch of error messages, and a sentence will always come out of their heads, "What the hell is this. If you're seeing it for the first time, you may not know what it's telling you. Although Python's Traceback messages look complicated, they're full of information that can help you diagnose and fix the cause of an exception in your code, as well as locate which line of code in which file is in error. In addition, we are often asked in interviews about the types of exceptions in Python and their meanings, so let's understand them in detail.

What is Traceback

Traceback is a report of Python error messages. While other programming languages have different names for it, including stack trace, stack traceback, backtrac, etc., in Python we use the term Traceback, and the error messages I'll be referring to later are all Tracebacks.
When your program causes an exception, Python will print Traceback to help you know what went wrong. Here's an example to illustrate this situation

# 
def greet(someone ):
  print('Hello, ' + someon )
 
greet('Chad')

Here we first define the function greet, then pass in the parameter someone, then within the function, a print statement where someon is an undefined variable, and then through greet ('Chad'), we call the greet function we just defined, and after running it, we get the following error message.

(The beginning of an error message in Python is Traceback.)

Traceback  (most  recent  call  last ):
  File  '/Users/chenxiangan/pythonproject/demo/', line  5, in  <module>
    greet ('Chad')
  File  '/Users/chenxiangan/pythonproject/demo/', line  3, in  greet
    print ('Hello, ' + someon )
NameError: name  'someon' is  not  defined

This error output contains all the information needed to diagnose the problem. The last line of the error output generally tells you what type of exception was thrown and some relevant information about the exception. The first few lines of the error message indicate the code file that threw the exception and the number of lines.

In the above error message, the exception type is NameError, meaning that the name uses a reference to an undefined name (variable, function, class). In this case, the referenced name is someon.

Usually you can find the cause of the error by looking at the last line of the error message. Then we search the code for the name 'someon' in the error message and realize that it is a misspelling, then we change it to someone.

However, some codes have more complex error messages than this.

How to read Python's Traceback messages?

Python's Traceback can yield a lot of useful information when you want to determine why your code threw an exception. Here's a list of common tracebacks to help you understand the different information contained in Tracebac.

Python Traceback Information at a Glance

Every Python Traceback message has several important parts. The following figure shows the components.

  • Blue box:The last line of the Traceback is the error message line. It contains the name of the exception raised.
  • Green box: the name of the exception is followed by an error message. This message usually contains useful information for understanding what raised the exception.
  • Yellow box: reading order from bottom to top, the bottom of the information, is to throw an error in the outermost position, the higher the depth of the code call the deeper.

There are then two error messages for each file in error, the first line is File followed immediately by the path to the file, then the number of lines, and finally the module or method name.
Click on the link to the file in Pycharm to locate the error.

Underlined in red: the second line is the actual code statement that is executed.

A concrete example

There are specific Traceback messages that can help us better understand and see what information the Traceback will provide.

The following sample code illustrates the information provided by Traceback in Python.

def who_to_greet(person ):
  return person if person else input ('Greet who? ')

def greet(someone, greeting='Hello'):
  print(greeting + ', ' + who_to_greet (someone ))

def greet_many(people):
  for person in people:
    try:
      greet(person )
    except Exception:
      print ('hi, ' + person )

Define a who_to_greet function that takes a value of person and returns the result based on an if judgment.

Then, the greet function takes a someone and an optional greeting, and calls the print function, which calls the who_to_greet function and passes in the argument someone.

Finally, greet_many(), will iterate through the list of people and call the greet function. If an exception is thrown by calling greet(), a simple greeting is printed.

As long as the correct inputs are provided, this code does not have any errors that could cause an exception to be raised.

If you call the greet function in and pass in a value (e.g. greet ('chad', greting = 'Yo')), then you will get the following Traceback message

Traceback  (most  recent  call  last ):
  File  '/Users/chenxiangan/pythonproject/demo/', line  17, in  <module>
    greet ('chad',greting  ='Yo')
TypeError: greet () got  an  unexpected  keyword  argument  'greting'

We said earlier that reading Python's Traceback information is done from the bottom up, so let's look at it together again here.

The first thing we need to look at is the last line of the error message, by which we can know the type of error and some of the causes of the error.

Meaning: The call to greet() was made with an unknown parameter, which is greting.

Okay, and then we need to keep looking up to see the line that caused the exception. What we see in this example is the exact code that calls the greet method.

Its top line provides the path to the file where the code is located, as well as the line number of the code file and the module it is in. (The exact location can be located in Pycharm by clicking on the file link)

In this example, since our code doesn't use any other Python modules, we see <module> here, which indicates that the location is the file being executed.

If you call the greet method from a different file and in a different way, you will get different traceback information, so here's how to execute the greet method by importing a file. Let's see the difference in the results.

#  
from greetings import greet 
greet (1)

Result after running.

Traceback  (most  recent  call  last ):
  File  '/Users/chenxiangan/pythonproject/demo/', line  3, in  <module>
    greet (1)
  File  '/Users/chenxiangan/pythonproject/demo/', line  6, in  greet
    print (greeting  + ', ' + who_to_greet (someone ))
TypeError: can  only  concatenate  str  (not  'int') to  str

The exception raised in this example is also a type error, but this time the message is less helpful. It just tells you that somewhere in the code, strings can only be concatenated with strings, not int.

Moving up, you can see the lines of code that were executed. Then there is the file and line number of the code. However, this time we get not, but the name of the function being executed greet().

Then continuing up the line of code executed, we see that the problem code is that the greet() function call was passed an integer.

Sometimes after raising an exception, another part of the code catches the exception and causes it. In this case, Python outputs all the exceptions in the order they were received, with the outermost exception at the bottom of the Traceback contents.

It may seem a bit confusing, so here's an illustration using a concrete example.

The code for calling greet_many in a file is as follows.

greet_many (['Chad', 'Dan', 1])

The error message output after running is as follows

Hello, Chad
Hello, Dan
Traceback  (most  recent  call  last ):
  File  '/Users/chenxiangan/pythonproject/demo/', line  12, in  greet_many
    greet (person )
  File  '/Users/chenxiangan/pythonproject/demo/', line  6, in  greet
    print (greeting  + ', ' + who_to_greet (someone ))
TypeError: can  only  concatenate  str  (not  'int') to  str

During  handling  of  the  above  exception, another  exception  occurred:

Traceback  (most  recent  call  last ):
  File  '/Users/chenxiangan/pythonproject/demo/', line  17, in  <module>
    greet_many (['Chad', 'Dan', 1])
  File  '/Users/chenxiangan/pythonproject/demo/', line  14, in  greet_many
    print ('hi, ' + person )
TypeError: can  only  concatenate  str  (not  'int') to  str

emmmmm, this time seems not the same, than the previous content a lot more, and there are two Traceback block information, what does this mean?

Pay attention to that.

During  handling  of  the  above  exception, another  exception  occurred:

It means: during the handling of the above exception, another exception occurred. It simply means that there was an exception in the code in the except. That's what caused this phenomenon.

The example is that on the third loop person=1 then the strings hi and 1 cannot be concatenated and the exception is thrown again.

Viewing all the error message output can help you understand the real cause of the exception.

Sometimes, when you see the last exception was raised, and the resulting error message, you may still not see what went wrong. For example, this example, directly through the last exception can not see exactly where the problem is, this time to consider continuing to look up.

to this article on the python error traceback interpretation of the article is introduced to this, more related python traceback content please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!