Reputation: 1281
suppose i have this directory structure
package /
__init__.py
cpackage.py
subpackage1/
__init__.py
subpack1_call.py
/lib
__init__.py
sub_lib.py
subpackage2/
__init__.py
subpack2_call.py
i want to import cpackage in subpackage1 and subpackage2 which i am unable to import i get valuename error and module not found errors
where as i can easily do this in subpackage1
from lib.sub_lib import hello_pr
hello_pr()
here there is no error and hello_pr prints what i defined in sub_lib but i am unable to move up the directory, where as in above case i can easily move down the directory structure
what am i missing . i have looked into so many solutions in this site and pydoc, maybe i am missing something, cause nothing seemed to be working for
Upvotes: 1
Views: 1918
Reputation:
If you can import lib.sub_lib, it means your PYTHONPATH points to subpackage1. It should point to the directory containing package, then you'll be able to import package.cpackage, package.subpackage1.lib.sub_lib, etc.
You can also point your PYTHONPATH to cpackage, then remove init.py in this directory as it's useless, and you can import cpackage, subpackage1.lib.sub_lib, etc.
The basic rule is: if PYTHONPATH=dir, then
dir\
bob.py
sub\
__init__.py
bib.py
inner\
__init__.py
bub.py
import bob
import sub (will import sub\__init__.py)
import sub.bib (will import sub\__init__.py then bib.py)
import sub.inner (will import sub\__init__.py then sub\inner\__init__.py)
import sub.inner.bub (will import sub\__init__.py then sub\inner\__init__.py
and finally bub.py)
Upvotes: 1
Reputation: 798716
After parsing and reparsing your question a few times, I've decided that what you're looking for is relative imports.
from ..cpackage import somename
Upvotes: 1