Search code examples
pythonpython-3.ximporterror

Why can't I import without getting an error about another python file? ("partially initialized module has no attribute")


I'm trying to import the requests module to get familiar with bs4, but the request module in the file I'm currently working in is grayed out so it isn't being recognized as a module. When I run the almost empty program, I get an error for an unrelated python file within my project.

Should I individually store each python file I make inside of a separate folder? Both of these files are inside of the same project folder.

import requests

response = get('https://www.newegg.ca/p/N82E16868105274')

print(response.raise_for_status())

Error:

  Traceback (most recent call last):
      File "C:\Users\Denze\MyPythonScripts\Webscraping learning\beautifulsoup tests.py", line 1, in <module>
        import requests
      File "C:\Users\Denze\MyPythonScripts\requests.py", line 3, in <module>
        res = requests.get('')
    AttributeError: partially initialized module 'requests' has no attribute 'get' (most likely due to a circular import)
    
    Process finished with exit code 1

The other code in question that I think is causing my error:

import requests

res = requests.get('')

playFile = ('TestDownload.txt', 'wb')

for chunk in res.iter_content(100000):
    playFile.write(chunk)

playFile.close()

Solution

  • You have a name collision. You're not importing the requests library, you're importing your script.

    You wanted to do the following with your imports:

    MyPythonScripts\beautifulsoup tests.py 
        → requests.get() (the library)
    

    What you're doing instead is:

    MyPythonScripts\beautifulsoup tests.py 
        → MyPythonScripts\requests.py 
        → MyPythonScripts\requests.py .get() (the same file again)
    

    That's the "circular import" that is mentioned in the traceback. The module imports itself and tries to use an attribute that isn't there before it finishes "executing", so the interpreter thinks it's due to the unfinished initialization

    Raname MyPythonScripts\requests.py to something else and it should work.