2

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
1
  • 1
    Note that __init__.py files need not be empty. If they aren't empty they are executed during importing. This means that mod1 must be imported in your case because mod1/__init__.py could 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. Commented Nov 7, 2015 at 13:17

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.