0

When I have the following packages:

src
   /__main__.py
   /dir1
        /__init__.py
        /main_code1.py
        /service.py
        /config.py
   /dir2
       /__init__.py
       /maincode2.py
   /dir3
       /__init__.py
       /maincode3.py

What is the difference between using the following statement in the file __main__.py

import dir1

&

from dir1 import *

&

from dir1 import main_code1

The second question is: How to import maincode3.py (present in dir3) to the maincode.py script present in dir1? I am searching for way without changing sys.path list.

Alex
  • 1,416
  • 4
  • 16
  • 42
tabebqena
  • 1,204
  • 1
  • 13
  • 23

2 Answers2

2
import dir1

Imports dir1's __init__.py. You can access whatever is there using dir1.my_var_from_dir1_init. You cannot access the modules, only what's on dir1's __init__.

from dir1 import *

Imports the modules specified on the __all__ variable defined on dir1's __init__.py. If there isn't such variable, then it imports all of dir1's modules. You can access them directly, like main_code1.myvar.

from dir1 import maincode

Assuming it's a typo and you actually have a maincode module or class, it imports the maincode module/class from dir1. You can access it directly like mentioned above.

Note that each option imports dir1's __init__.py, implicitly or explicitly. If you import the modules on __init__.py, then using import dir1 will allow you to use dir1.module.


To import dir3's maincode3 to maincode.py, simply use from dir3 import maincode3. Just be careful with circular imports, which will generate an import error. You can also take a look on relative imports.

Community
  • 1
  • 1
Alex
  • 1,416
  • 4
  • 16
  • 42
  • when I use (from dir1 import maincode1) and the __init__.py contain line like :(import service , config ) , Is the modules config & service imported or not ?? – tabebqena Aug 28 '13 at 22:24
  • Why don't you try it yourself? They are imported, but I guess you can't access them directly. – Alex Aug 28 '13 at 22:28
1
  • import dir1 will import dir1/__init__.py file.
  • from dir1 import *: all modules inside dir1 will be imported. Access "main_code1" without using the "dir." before.
  • from dir1 import main_code1 will only import the main_code1 module.

If the __main__.py file is importing all the other modules, then you can access dir3.maincode3.py from dir1.main_code1.py simply doing something like:

import dir3.maincode3

cdonts
  • 9,304
  • 4
  • 46
  • 72