6 Common Mistakes While Importing Modules & Their Fixes! (Python)

In this article let us look at the 6 common mistakes you can run into while importing modules in Python and how to fix each of those!

Before we proceed I would also like to invite you to check out our video on the 3 simple steps you can take to solve any exception in Python!

Cause#1: Incorrect Module Name

This is by far the most common mistake faced by both beginners and experienced alike!

To Err is Human

Human errors are part and parcel of programming, you just need to develop the patience to deal with them when they occur!

Here is an example

import mth
print(math.sqrt(81))

OUTPUT:

Traceback (most recent call last):
  File "/home/main.py", line 1, in <module>
    import mth
ModuleNotFoundError: No module named 'mth'

In this example, we misspelled the ‘math’ module as ‘mth’ so we encountered a ModuleNotFoundError. Note that ModuleNotFoundError is a subclass of the ImportError class.

Here’s the correct program:

import math
print(math.sqrt(81))

Fix for Cause#1:

The fix requires a little bit of patience and some focus to double-check the spelling to make sure that you have spelled the name of the module correctly!

After double-checking you are sure that the error still exists? Check out the following article for a strategic way of fixing ModuleNotFoundError!

ModuleNotFoundError: A Step By Step Troubleshooting Guide!

Cause#2: Using The Module Before Importing It

Alternatively, trying to use the module before you have called it leads to an error as well.

Here’s a simple example:

print(math.sqrt(81))
import math

OUTPUT:


Traceback (most recent call last):
  File "/home/main.py", line 1, in <module>
    print(math.sqrt(81))
NameError: name 'math' is not defined

A NameError is raised here as the interpreter does not recognize the what ‘math’ is in the first line.

Keep in mind that Python executes our programs starting from the top of the page, one line at a time.

Fix for Cause#2:

This is another simple case of human error and hence again it calls for some patience, focus and double-checking!

But sometimes double-checking will not be enough to fix the issue, if you fall into that category I suggest checking out the following article for a step-by-step process on how to fix NameError!

NameError: A Step By Step Troubleshooting Guide!

Cause#3: Import Something Does Not Exist!

An error can also be raised if you’re trying to use a class or a function that does not exist in an imported module. In other words, the module might exist but not the specific class/function that you’re looking for inside it.

Here’s a program file:

def func1():
    return ("This is function 1")
    
def func2():
    return ("This is function 2")

In our above module my_func, we have defined two functions: func1() and func2()

Now let’s try importing and calling it:

import my_func
print(my_func.func1())
print(my_func.func2())
print(my_func.func3())

OUTPUT:

This is function 1
This is function 2
Traceback (most recent call last):
  File "/home/main.py", line 4, in <module>
    print(my_func.func3())
AttributeError: module 'my_func' has no attribute 'func3'. Did you mean: 'func1'?

We see that we get the outputs of func1 and func2 when called but it raises an error when we call func3. That is because there exists no function called func3.

If you have a large program and your main program is importing all these files and if you run into this scenario, just take a look at the message in the error output to fix it.

Here is a pro tip for you, to fix not just NameError but any error in Python. Whenever your program crashes with an Exception, (take a deep breath and) have a look at the huge wall of error text that just got printed on your screen!

There is actually a lot of information contained in the error message, if you wish to learn the tricks then set aside 10mins of your time and read the following article!

Python: Details contained in an Exception

In the above example, the last line says AttributeError: module ‘my_func has no attribute ‘func3‘. Did you mean: ‘func1’?

Now that we know that the relevant module is my_func, all that is left to do is to check if the my_func module has the attribute the error message specifies, func3 in this case.

Fix for Cause#3:

You can use the in-built help( ) method to verify if the module you are importing has all the necessary attributes!

After importing the math module with the following line of code

import math

I can print whatever is inside math using the help( ) function as follows

If you are looking for a step-by-step guide to deal with AttributeError you can use the strategy outlined in the following article!

AttributeError: A Step By Step Troubleshooting Guide!

Cause#4: Module Is Not Installed In Your System

One other simple way an error will be raised is when the module you’re trying to import is simply not available in the standard Python library. 

Let’s try to understand this with two libraries, math, and matplotlib:

If I try to import the math module:

import math

It works smoothly without any problems.

But that’s not the case with matplotlib:

import matplotlib

It raised an error saying

Exception has occurred: ModuleNotFoundError
No module named 'matplotlib'
  File "C:\Users\Jamal\OneDrive\Desktop\import matplotlib.py", line 1, in <module>
    import matplotlib
ModuleNotFoundError: No module named 'matplotlib'

What’s happening here is, the math module is something that comes alongside Python when you download it, it exists in the Python library.

This is not the case for matplotlib, it does not come with the Python library. Instead, you need to download it manually.

The error was raised this time because

I hadn’t downloaded the library → The interpreter tried to access it → It did not find it –> hence it raised an error.

embeddedinventor.com

Fix for Cause#4:

To download and use libraries such as these, it’s best to first visit the library’s documentation and follow the instructions on how to install their library in your system!

We have an entire article dedicated to troubleshooting ModuleNotFoundError that gives you a step-by-step guide to fix that error once and for all!

You can find it in the link below!

ModuleNotFoundError: A Step By Step Troubleshooting Guide!

Cause#5: Circular Dependency

The circular dependency issue happens when you have two files that are mutually dependent, in other words, dependent on each other. 

An example code would make understanding easier: 

Let’s say I have two Python files, the main file and a file named myfile:

from myfile import Class2
class Class1:
    obj = Class2()
from main import Class1
class Class2:
    obj = Class1()

In the main file:

To create an object obj, we depend on class2 from the myfile module

In the myfile file:

To create an object obj, we depend on class1 from the main module

This ends up in a circle and leads to nowhere (except an error!)

OUTPUT:

Traceback (most recent call last):
  File "/home/main.py", line 1, in <module>
    from myfile import Class2
  File "/home/myfile.py", line 1, in <module>
    from main import Class1
  File "/home/main.py", line 1, in <module>
    from myfile import Class2
ImportError: cannot import name 'Class2' from partially initialized module 'myfile' (most likely due to a circular import) (/home/myfile.py)

Fix for Cause#5:

Now that we have understood the issue, we need to move stuff around so that we don’t end up with a circular dependency. If your code looks something like ours, you can always have a single class with the common features of classes 1 and 2 and inherit that one in Class1 and Class2 to get the required functionality.

Cause#6: Corrupted Module

If the module you’re importing has a syntax error or is corrupted, just importing it would lead to an error.

Here’s a module I’ve made that clearly contains a syntax error

def my_func():
    print("hello world')
from helloworld import my_func
Traceback (most recent call last):
  File "/home/main.py", line 1, in <module>
    from helloworld import my_func
  File "/home/helloworld.py", line 2
    print("hello world')
          ^
SyntaxError: unterminated string literal (detected at line 2)

Fix for Cause#6:

If you are facing SyntaxError, the fix is usually pretty simple. If you need a step-by-step approach, you can use the following article to help you on your way!

SyntaxError: A Step By Step Troubleshooting Guide!

For the next step in your Python journey I invite you to master some of the most common errors you will run into in your daily life as a Python developer. We have compiled a list of just 7 exceptions that you need to focus on if you wish to gain mastery of Exceptions in Python!

7 Most Common In-Built Exceptions in Python!

If you are a visual learner here is a YouTube video that we made on that same topic!

And with that, I will end this article.

Congratulations on making it to the end of the article, not many have the perseverance to do so!

I hope you enjoyed reading this article and found it useful!

Feel free to share it with your friends and colleagues!

If your thirst for knowledge has not been quenched yet, here are some related articles that might spark your interest!

Related Articles

Python: Details contained in an Exception

Python: “try-except-else-finally” Usage Explained!

Mutable and Immutable Data Types in python explain using examples

7 Most Common In-Built Exceptions in Python!

Photo of author
Editor
Balaji Gunasekaran
Balaji Gunasekaran is a Senior Software Engineer with a Master of Science degree in Mechatronics and a bachelor’s degree in Electrical and Electronics Engineering. He loves to write about tech and has written more than 300 articles. He has also published the book “Cracking the Embedded Software Engineering Interview”. You can follow him on LinkedIn