I'm still trying to figure out how to create packages, here is a file structure that demonstrates my problem:
/main_package/
__init__.py
script1.py
sub_package/
__init__.py
model.py
Within the __init__.py
of the main_package
let's say I have:
import main_package.script1
...
And within script1.py
I have:
from sub_package import model
...
This doesn't 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 the from sub_package import model
within script1.py
doesn't 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 a dumb mistake somewhere, but what would be the problem way to fix my issue?
UPDATE: Ok some people asked exactly how this happens, so I'll post the actually error message I'm getting and my actual structure and procedure. Sorry, the names are now changed up from the above.
Here is my real package structure for the packages which 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 (i.e ipython script.py [args]
) and get the following error message (I erased everything that comes after the problem 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 exists by the way.
from .sub_package import model
give?script1.py
is executed. Is it imported from some other program or is it run directly as a script?main_package/__init__.py
doingfrom . import script1
andmain_package/script1.py
doingfrom .sub_package import model
, it works for me. What version of python do you have? What's your current directory when you run the test? I was in the parent ofmain_package
so that the package was found correctly.Models.model_main
inModels.__init__
, that can't work.