Let's assume I have the following structure.
main.py
/mod1
__init__.py
mod1.py
/mod2
__init__.py
mod2.py
And I have the following line in main.py.
import mod1.mod2
In this case does mod1 also get imported?
Peter Mortensen
31.3k22 gold badges110 silver badges134 bronze badges
asked Nov 7, 2015 at 11:50
BendEg
21.3k17 gold badges69 silver badges135 bronze badges
2 Answers 2
Yes; mod1 is imported as well, and you can access mod1 solely as mod1 within your code if you do not write an alias like this import mod1.mod2 as mod2.
Python needs to import the modules consecutively so that it is able to import last module. You can test this by putting print statements in your __init__.py files
answered Nov 7, 2015 at 12:12
Ozan
1,0841 gold badge9 silver badges24 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Yes. Try this in the interpreter:
import os.path
dir
os
As this shows, os is present in the main namespace.
answered Nov 7, 2015 at 12:04
Tom Zych
13.7k9 gold badges38 silver badges55 bronze badges
Comments
lang-py
__init__.pyfiles need not be empty. If they aren't empty they are executed during importing. This means thatmod1must be imported in your case becausemod1/__init__.pycould setup some resource or stuff like that required by (e.g.)mod2. Also modules have reeferences to their packages, so the parent modules must be imported for the references to exist.