Importing a library from (or near) a script with the same name raises “AttributeError: module has no attribute” or an ImportError or NameError

This happens because your local module named requests.py shadows the installed requests module you are trying to use. The current directory is prepended to sys.path, so the local name takes precedence over the installed name.

An extra debugging tip when this comes up is to look at the Traceback carefully, and realize that the name of your script in question is matching the module you are trying to import:

Notice the name you used in your script:

File "/Users/me/dev/rough/requests.py", line 1, in <module>

The module you are trying to import: requests

Rename your module to something else to avoid the name collision.

Python may generate a requests.pyc file next to your requests.py file (in the __pycache__ directory in Python 3). Remove that as well after your rename, as the interpreter will still reference that file, re-producing the error. However, the pyc file in __pycache__ should not affect your code if the py file has been removed.

In the example, renaming the file to my_requests.py, removing requests.pyc, and running again successfully prints <Response [200]>.


Note: This doesn’t only happen when naming your file as the module you are trying to import. This can also happen if you name your file the same as a module imported by a module you import directly. For example, having a file called copy.py and trying to import pandas from there, will give

ImportError: cannot import name 'copy' from 'copy'

That is because pandas imports copy. There is no magic solution here as you can’t know all the modules’ names in the world, but a rule of thumb is to try to make names of modules as unique as possible and try to change the name whenever you get such error.

Leave a Comment