Importing installed package from script with the same name raises “AttributeError: module has no attribute” or “ImportError: cannot import name”

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]>.

Leave a Comment