Solving the errors “AttributeError: module has no attribute” or “ImportError: cannot import name” in Python

“AttributeError: module has no attribute” or “ImportError: cannot import name” happens when a local module shadows the installed module we want to use.

In this article I am going to explain why this error is happening in the first place and how to fix it using multiple solutions which may solve the problem.

Describing “AttributeError: module has no attribute” or “ImportError: cannot import name” in Python

First of all we should understand that the error is happening because the local name of the module we are trying to use is taking precedent over the installed name of the module.

Pay attention to the error and notice that the name of the script is the same as the name of the module we are importing.

Solution 1 : Renaming the .py file.

First of all, let us replicate the error by trying to get the URL of google

                                                                       #
import requests
res = requests.get('http://www.google.com')
print(res)
                                                                       #

The resulting error is as follows

                                                                       #
Traceback (most recent call last):
    import requests
    requests.get('http://www.google.com')
AttributeError: module 'requests' has no attribute 'get'
                                                                       #

Notice that requests.py is the name of our script and it matches requests as in requests.get inside our code

The best solution is very simple, we should avoid the confusion by renaming the .py file.

And voila the error should be gone by now.

Solution 2 : solve module conflict and more

The solution above is universal and should solve the majority of the cases, if you are an unlucky fellow, the solution bellow may work for you.

Sometimes the error is so confusing that even with a lot of investigation it is hard to spot the root of the problem.

For example you are not even making a mistake by having the name of your file in conflict with the name of a module we are trying to use inside the same file.

The error can occur even when you have a different script inside the same directory of your current script and inside your script you have a module in conflict with that other file.

If your code is very long make sure you use CTRL + F to search for all the names of the py files inside your directory in order to make sure there is no conflict inside your script.

Summing-up

This is the end of our article, this error could be confusing but with a little bit of investigating the error could be solved easily by renaming your files, thank you for reading.

To support us consider donating to our Kofi account above. Keep coding, keep learning and cheers.

If you want to learn more about Python, please check out the Python Documentation : https://docs.python.org/3/