Reputation: 68868
Consider this simple folder structure:
root
Package1
x.py
y.py
Package2
z.py
Examples
main.py
Now our requirements are:
Below is what works:
x.py
import y
def x():
y()
y.py
def y():
pass
z.py
import package1.y as y
def z():
y.y()
main.py
import sys
from os import path
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
import package1.y as y
import package2.z as z
y.y()
z.z()
Questions:
sys.path
in main
because it strongly binds assumptions about package locations inside code file. Is there any way around that?as y
part in import package1.y as y
. Is there any way around that?Upvotes: 3
Views: 318
Reputation: 40023
As always, there are two separate steps:
package1
and package2
(and sys
, os
, etc.), but not “Examples” which is not a package (because main.py
is not a module).sys.path
appropriately before any of your code ever runs. If it's your own (uninstalled) code, there are places you can put it, or you can write an easy shell script wrapper to set PYTHONPATH
for your python
process.So the answers to your questions are
x.py
you write from . import y
. (Python 2 supports this and 3 requires it.)sys.path
depends on your packaging/environment system. The traditional way is to set the PYTHONPATH
environment variable for the python
process, but there are other ways involving things like the site
module.from package1 import y
is the usual way to name things only once.Upvotes: 1