Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImportError: cannot import module

The package looks like this:

  • main.py
  • HTTPQuery.py
  • SmartDownload.py

in main.py I run from SmartDownload import DownloadFile.

in Smartdownload.py I run from HTTPQuery import Is_ServerSupportHTTPRange

in HTTPQuery I run from SmartDownload import DownloadFile

It seems that I get stuck in a loop, because this is the error:

Traceback (most recent call last):
  File "C:\Scripts\mp3grabber\main.py", line 13, in <module>
    import HTTPQuery
  File "C:\Scripts\mp3grabber\HTTPQuery.py", line 6, in <module>
    from SmartDownload import DownloadFile
  File "C:\Scripts\mp3grabber\SmartDownload.py", line 3, in <module>
    from HTTPQuery import Is_ServerSupportHTTPRange
ImportError: cannot import name Is_ServerSupportHTTPRange

But I must import second file's functions into the third file and vice-versa.

What can I do?

like image 320
iTayb Avatar asked Apr 14 '26 06:04

iTayb


2 Answers

As you suggest, there is a circular dependency between HTTPQuery and SmartDownload. The easy fix is to move the import into the functions that require it, e.g.

# SmartDownload.py
def download(url):
    from HTTPQuery import Is_ServerSupportHTTPRange
    ...

A better solution might be to reorganize your modules. If there is no reasonable way to remove HTTPQuery's dependence on SmartDownload or vice versa, consider merging them into one module.

like image 142
Daniel Lubarov Avatar answered Apr 15 '26 19:04

Daniel Lubarov


Your best option is to re-organize the dependencies so you don't have this circular import problem. Barring that, you may be able to simply move the line from SmartDownload import DownloadFile to the bottom of your HTTPQuery.py file to break the loop.

There's a bit of discussion on circular imports here.

like image 37
Brian Elliott Avatar answered Apr 15 '26 21:04

Brian Elliott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!