Python imports. Again…
I have this file structure:
[test]
start.py (from scripts import main)
[scripts]
__init__.py (empty)
main.py (from . import install)
install.py (from scripts import main # or # from . import main)
I get import error:
vic@wic:~/projects/test$ python3 start.py
Traceback (most recent call last):
File "start.py", line 2, in <module>
from scripts import main
File "/home/vic/projects/test/scripts/main.py", line 1, in <module>
from . import install
File "/home/vic/projects/test/scripts/install.py", line 1, in <module>
from scripts import main
ImportError: cannot import name main
vic@wic:~/projects/test$
I don’t understand: first time from scripts import main worked (by “worked” I mean it didn’t fail with ImportError), and second time the same code gives ImportError: cannot import name main
What is going on?
UPDATE:
My question is not about circular imports. I am confused by the fact that exactly the same code from scripts import main first time works ok and then second time fails.
I guess there is some internal import mechanism which i don’t understand.
First time a statement imports a module, second time exactly the same code tries to import a name from a module. How this works?
You created a circular import. You can’t do that. Avoid importing
mainfrominstall.What is happening is that a module, while being imported, is incomplete until the whole top level has been executed. If during that execution it imports another module that (directly or indirectly) tries to import the original module again, this will fail. The original module was not yet done importing yet.
In other words, you are creating a circular graph:
You need to re-arrange your code to not need to import from
mainfrom within yourscriptspackage.See What are the “best practices” for using import in a module? for some tips on how to handle this.