idjaw idjaw - 2 months ago 11
Python Question

Importing installed package from script raises "AttributeError: module has no attribute" or "ImportError: cannot import name"

I have a script named

requests.py
that imports the requests package. The script either can't access attributes from the package, or can't import them. Why isn't this working and how do I fix it?

The following code raises an
AttributeError
.

import requests

res = requests.get('http://www.google.ca')
print(res)




Traceback (most recent call last):
File "/Users/me/dev/rough/requests.py", line 1, in <module>
import requests
File "/Users/me/dev/rough/requests.py", line 3, in <module>
requests.get('http://www.google.ca')
AttributeError: module 'requests' has no attribute 'get'


The following code raises an
ImportError
.

from requests import get

res = get('http://www.google.ca')
print(res)




Traceback (most recent call last):
File "requests.py", line 1, in <module>
from requests import get
File "/Users/me/dev/rough/requests.py", line 1, in <module>
from requests import get
ImportError: cannot import name 'get'


The following code raises an
ImportError
.

from requests.auth import AuthBase

class PizzaAuth(AuthBase):
"""Attaches HTTP Pizza Authentication to the given Request object."""
def __init__(self, username):
# setup any auth-related data here
self.username = username

def __call__(self, r):
# modify and return the request
r.headers['X-Pizza'] = self.username
return r




Traceback (most recent call last):
File "requests.py", line 1, in <module>
from requests.auth import AuthBase
File "/Users/me/dev/rough/requests.py", line 1, in <module>
from requests.auth import AuthBase
ImportError: No module named 'requests.auth'; 'requests' is not a package

Answer

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.

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.

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

Comments