简体   繁体   中英

Python: importing a sub-package module from both the sub-package and the main package

Here we go with my first ever stackoverflow quesion. I did search for an answer, but couldn't find a clear one. Here's the situation. I've got a structure like this:

myapp
    package/
         __init.py__
         main.py
         mod1.py
         mod2.py

Now, in this scenario, from main.py I am importing mod1.py, which also needs to be imported by mod2.py. Everything works fine, my imports look like this:

main.py:

from mod1 import Class1

mod2.py:

from mod1 import Class1

However, I need to move my main.py to the main folder structure, like this:

myapp
    main.py
    package/
         __init.py__
         mod1.py
         mod2.py

And now what happens is that of course I need to change the way I import mod1 inside main.py:

from package.mod1 import Class1

However, what also happens is that in order not to get an "ImportError: No module named 'mod1'", I have make the same type of change inside mod2.py:

from package.mod1 import Class1

Why is that? mod2 is in the same folder/pakcage as mod1, so why - upon modifying main.py - am I expected to modify my import inside mod2?

The reason this is happening is because how python looks for modules and packages when you run a python script as the __main__ script.

When you run python main.py , python will add the parent directory of main.py to the pythonpath, meaning packages and modules within the directory will be importable. When you moved main.py, you changed the directory that was added to the pythonpath.

Generally, you don't want to rely on this mechanism for importing your modules, because it doesn't allow you to move your script and your package and modules are only importable when running that main script. What you should do is make sure your package is installed into a directory that is already in the pythonpath. There are several ways of doing this, but the most common is to create a setup.py script and actually install your python package for the python installation on your computer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM