Debugging code can be a tedious and time-consuming task, but having a clear traceback can greatly speed up the process. Python 3.11 introduces fine-grained error locations in tracebacks, allowing developers to quickly identify the exact location of errors.
In this post, we’ll explore the difference in traceback between Python 3.9 and Python 3.11 using an example.
Example Code
Let’s consider the following Python code with a typo in the variable name:
def greet(name):
greeting = "Hello, " + name + "!"
print(greetng) # Error: Typo in variable name
greet("Khuyen")
Traceback in Python 3.9
When we run this code in Python 3.9, we get the following traceback:
Traceback (most recent call last):
File "/Users/khuyentran/book/Efficient_Python_tricks_and_tools_for_data_scientists/Chapter1/trackback_test.py", line 5, in <module>
greet("Khuyen")
File "/Users/khuyentran/book/Efficient_Python_tricks_and_tools_for_data_scientists/Chapter1/trackback_test.py", line 3, in greet
print(greetng) # Error: Typo in variable name
NameError: name 'greetng' is not defined
Traceback in Python 3.11
Now, let’s run the same code in Python 3.11:
Traceback (most recent call last):
File "/Users/khuyentran/book/Efficient_Python_tricks_and_tools_for_data_scientists/Chapter1/trackback_test.py", line 5, in <module>
greet("Khuyen")
File "/Users/khuyentran/book/Efficient_Python_tricks_and_tools_for_data_scientists/Chapter1/trackback_test.py", line 3, in greet
print(greetng) # Error: Typo in variable name
^^^^^^^
NameError: name 'greetng' is not defined. Did you mean: 'greeting'?
As you can see, Python 3.11 provides a more detailed traceback with fine-grained error locations. The ^^^^^^^
symbol points to the exact location of the error, making it easier to identify and fix the issue. Additionally, Python 3.11 suggests a possible correction, which can be helpful in cases where the error is due to a typo.