Python: import a submodule or subpackage from a single package

I'm still trying to figure out how to create packages, here is the file structure that demonstrates my problem:

/main_package/ __init__.py script1.py sub_package/ __init__.py model.py 

In __init__.py main_package let's say that I have:

 import main_package.script1 ... 

And inside script1.py I have:

 from sub_package import model ... 

This does not work. When I try to import main_package , I get an error in the following set of calls: import main_package.script1 from sub_package import model

Apparently, from sub_package import model inside script1.py does not work.

I tried the following:

from main_package.sub_package import model

from . import sub_package.model

from .sub_package import model

And none of them work. Sorry if I'm making something stupid mistake, but what could be the problem to fix my problem?


UPDATE . Ok, some people asked how this happens, so I will post the error message I get and my actual structure and procedure. Sorry, the names are now changed from the above.

Here is my real package structure for packages that cause an error:

 script.py /MCMC2/ __init__.py main_script.py ExoData.py Models/ __init__.py model_main.py 

I run script.py in the terminal (for example ipython script.py [args] ) and get the following error message (I deleted everything that appeared after the error messages and replaced it with ... to make it clearer) .

 ImportError Traceback (most recent call last) /home/usr/script.py in <module>() 1 import pymc ----> 2 from MCMC2 import ExoData ... /home/usr/MCMC2/__init__.py in <module>() ... ----> 4 import MCMC2.main_script ... /home/usr/MCMC2/main_script.py in <module>() 1 try: from Models import model_main ----> 2 except: from .Models import model_main ... /home/usr/MCMC2/Models/__init__.py in <module>() ----> 1 import Models.model_main ... ImportError: No module named 'Models' 

Models definitely exist, by the way.

+5
source share
1 answer

Well, it looks like I'm confused with the whole structure of the package. Referring to the structure in the update - in the Models __init__.py file, I did the import as import Models.model_main , etc. .... For this I needed from . import model_main from . import model_main . Thanks for the help, by the way.

0
source

Source: https://habr.com/ru/post/1258763/


All Articles