Learn cause for Traceback (most recent call last): with a possible Fix

Traceback is an error report occurring while executing Python code that throws an exception. It provides us traceback information about issues caused due to a certain piece of code.

Other programming languages such as java etc also throw such exceptions known as stack trace that we can diagnose by looking into error details with file name, line number, and executed code block (function, params, or another statement).

Traceback is very important for developers to know about problems containing information such as file name, function call, line number, and exception name. For beginners, traceback might be a little complicated to understand initially but it's a learning way to understand the problem with error reported and resolve it accordingly.

In python, it’s good to go through errors reported from bottom to top.

Let’s understand Traceback (most recent call last): with the following example:

def introduce():
	return "Hello, I'm Test python script"

print(introduces())
 

Result:

  File "test.py", line 4, in <module>
    print(introduces())
NameError: name 'introduces' is not defined
        

Explanation: Here introduces() function is not defined in the program. This kind of error generally causes spelling/typing mistakes.

Now let’s understand the traceback error report in detail:

Throw Traceback error message as below:

Line 1: File "test.py", line 5, in
Exception caused at line number 5 of script test.py

Line 2: print(introduces())
Pointing code from where issue generated

Line 3: NameError: name 'introduces' is not defined
Contains traceback Exception name as “NameError”. With error message as “name 'introduces' is not defined” which is self-explanatory.

Note. NameError is reported if python tries to evaluate a variable, function, disc, etc which is not defined but used in the code block. Like in the above program it tries to evaluate introduces function but this function does not exist.

Traceback most recent call last in python

Let’s explore some common exceptions we met during program execution such as:

1. IndexError: list index out of range

Index out of range exception raised when we try to fetch items from the list by an index that does not exist.

Following code demonstrate list index out of range

employee = ["John", "Peter", "Alex", "Camren"]
print(employee[4])
    

Result:

Traceback (most recent call last):
  File "test.py", line 2, in <module>
    print(employee[4])
IndexError: list index out of range

    

Explanation: Exception name as IndexError with error messages list index out of range. In the program, it tries to fetch values of the employee list that exist on index 4 but list employees have length 4 with index from 0 to 3. There is no item on index 4 therefore it complains once trying to run code employee[4].

Traceback (most recent call last): return error report containing line number and error name and relevant error message to identify the problem and apply fix accordingly.

Solution:

To avoid this index out-of-range issue we can check the condition before attempting index value

def getEmployee(index):
	employee = ["John", "Peter", "Alex", "Camren"]
	if(len(employee) <= index):
	 return "Index out of range"
	else:
	  return employee[index]

print(getEmployee(4))

    

Explanation:

Here we have a function getEmployee that receives index as argument and returns employee name based on a passing index. Condition len(employee) <= index check whether received index greater than or equal to the length of employee list. If the index is larger than the list length then it returns the message Index out of range else returns the employee name.

2. KeyError in the dictionary

KeyError is raised when we try to fetch an item usually from a dictionary that doesn’t exist.

Let’s understand with the following example code

def getEmployee(index):
	employee = {"J" : "John", "p" : "Peter", "A" : "Alex", "C" : "Camren"}
	return employee[index]

print(getEmployee("J"))

    

Result: John

Exaptation: All good. We have values associated with passing key J and return value as John.

What if we call the same function with another key that doesn’t exist. Evaluate for the key K as below

def getEmployee(index):
	employee = {"J" : "John", "p" : "Peter", "A" : "Alex", "C" : "Camren"}
	return employee[index]

print(getEmployee("K"))

    

Result:

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print(getEmployee("K"))
  File "test.py", line 3, in getEmployee
    return employee[index]
KeyError: 'K'
    

Explanation: It raised Traceback (most recent call last): error report as KeyError and notifying us about key “K” with some details about function call and line number.

Solution: We can avoid KeyError issues by applying the required condition before fetching dictionary elements as below

def getEmployee(key):
	employee = {"J" : "John", "P" : "Peter", "A" : "Alex", "C" : "Camren"}
	if key not in an employee:
	  return "Key Doesn't exist!"
	else:
	  return employee[key]

print(getEmployee("K"))
    

Result: Key Doesn't exist!

Explanation: Condition key not in employee checks whether a received key exists in a dictionary or not.

If it exists, it returns relevant value to the calling function otherwise it returns a user-defined message Key Doesn't exist!

3. Modulenotfounderror (ImportError: No module named requests )

ImportError is raised while the python interpreter can’t find the imported package in the python script. There can be multiple reasons behind Modulenotfounderror such as

  • Spelling/Typing mistake in the imported module name
  • The included package is not installed
  • The interpreter can’t find the path of the included module.

The following example program demonstrates Modulenotfounderror

import requests
x = requests.get('https://www.quizcure.com')
print(x.status_code)
    

Result:

Traceback (most recent call last):
  File "test.py", line 1, in <module>
    import requests
ImportError: No module named requests
    

Explanation:

Since requests are not installed on my server therefore while using the get function from requests package it complains and throws an exception as ImportError with the error message No module named requests.

Solution:

Install requests package.

pip install requests

4. NameError (undefined name error)

NameError (undefined name error) is generally caused due to following common reasons

  • Misspelled builtIn function name or user-defined function
  • Human errors typing while defining variable name, module name, class name within the local or global scope.
  • Accessing variable is out of its scope

Let’s understand with below program

Misspelled builtin function name or user-defined function

employee = ["John", "Peter", "Alex", "Camren"]

def getEmployee(index):
	if(len(employee) <= index):
	 return "Index out of range"
	else:
	  return employee[index]

print(getEmploye(2))
 

Result: NameError: name 'getEmploye' is not defined

Explanation: As we can see, the calling function in print is getEmploye instead of getEmployee. Therefore it raised a NameError here.

Undefined param name:

Below program demonstrate NameError for undefined variable

var = 'hello'
print(va)
 

Result: NameError: name 'va' is not defined

Explanation; Here we are trying to access variable va that is not defined in the program

Accessing variable is out of its scope:

Let’s understand with a below simple example

def inner():
  x = "inner Function"

print(x)
 

Result: NameError: name 'x' is not defined

What above code mean:

This inner variable x defined inside the function is only accessible within function scope because it is a local variable for function inner therefore it raises NameError while accessing outside of function scope.

5. TypeError

TypeError occurs when trying to execute an inappropriate object type operation. Following are common causes behind TypeError:

  • Performing non-identical object type operations.
  • Using string indices to access list elements instead of integers or slices.
  • Treating non-callable object as callable.

Performing non-identical object type operations.

def sum(num):
    print (num + 5)

sum("test")
 

Result: TypeError: can only concatenate str (not "int") to str

Explanation:

  • Created function sum to add received number to integer 5. Therefore function expects a num argument as an integer value.
  • Passing string value test while calling function sum here which causes TypeError with the self-explanatory message as can only concatenate str.

To fix this issue We need to ensure the same object type operation while adding numbers or concatenating strings.

Therefore following two programs will work fine:

def sum(num):
    print (num + "5")

sum("test")

Result: test5

def sum(num):
    print (num + 5)

sum(10)
 

Result: 15

Using string indices to access list elements instead of integers or slices

employee = ["John", "Peter", "Alex", "Camren"]

print(employee["1"])

Result: TypeError: list indices must be integers or slices, not str

Explanation:

  • Define a list of names.
  • Trying to access a list with string indices "1". We can see the result as it complains and raises TypeError with message list indices must be integers or slices, not str

To fix this issue we need to access a list with integer values.

print(employee[1])

Will print: Peter

Treating the non-callable object as callable

Let’s understand with below example code

txt = "hello"

def demo():
    global txt
    txt = "there"


demo()
print(txt())

Result: TypeError: 'str' object is not callable

Explanation:

  • Let’s suppose we have a function demo that is modifying global variable txt value within a function block.
  • Calling demo function to set global param with new value there Now here we trying to print txt and treat it as callable which complains and raise TypeError with error message as 'str' object is not callable

To fix, just print txt like

print(txt)

Result: there

Practice Multiple-Choice Questions

  • What will be the result for the following code?
    print(me)
    me="hello"
    
    Options are:
  • What is the output for the following code?
    def getEmployee(index):
    	employee = {"J" : "John" "p" : "Peter", "A" : "Alex", "C" : "Camren"}
    	return employee[index]
    
    print(getEmployee("J"))
    
    Options are:

Connect With Us

We hope you find this Post Insightful.

Please Follow Us and Stay tuned with upcoming blog posts and updates.

You May Like to Read

Python Articles for Beginners & Advanced Learners