I have my python code in a folder called "project", so my code files are in project/*.py. I want to have submodules within it, e.g.
project/code.py # where code lives
project/mymodule1 # where more code lives
project/mymodule2
each module directory has its own init.py file, e.g.
project/mymodule1/__init__.py
suppose I have a file "test.py" within mymodule1 (project/mymodule1/test.py) and I'd like to refer to something from "code", e.g. import the function "myfunc"
== project/mymodule1/test.py ==
from code import myfunc
the problem is that "code" will not be found unless the user has placed the "project/" directory in their PYTHONPATH. Is there a way to avoid this and use some kind of "relative path" to import myfunc, e.g.
from ../code import myfunc
basically, I don't want to force users of the code to alter the PYTHONPATH unless I can do it programmatically for them from within my script. I'd like it to work out of the box.
How can this be done? either solution is good: altering PYTHONPATH programmatically, or more ideally, refering to "code" using some kind of relative importing, since even though I don't know where "project/code.py" lives on the user's computer, I know where it is relative to "myfunc".
EDIT: Can someone please show proper example of intra-package import? I tried, from "mymodule1" to do:
from .. import foo
where "foo" is in code.py but it does not work. I have init.py in mymodule1, so:
project/code.py
project/mymodule1/__init__.py
project/mymodule1/module1_code.py
where module1_code.py tries to import foo, a function defined in "code.py".
EDIT: The main confusion I still have is that even after adopting the example given in response to my message, showing the project/sub1/test hierarchy, you still cannot "cd" into sub1 and do "python test.py" and have it work. The user has to be in the directory containing "project" and do "import project.sub1.test". I'd like this to work regardless of what directory the user is in. The user in this case has to execute the file "test.py", which lives in project/sub1/. So the test case is:
$ cd project/sub1
$ python test.py
which yields the error:
ValueError: Attempted relative import in non-package
how can this be fixed?
thanks.