I have the following:
ModuleFolder
|
|-->. ModuleFile.py .
|
'-->. TestsFolder .
|
'---> UnitTest1.py
I'm trying to import from the parent directory. In this case I am trying to run "UnitTest1.py" from the test folder, and import from the directory immediately above it (the file "ModuleFile.py").
- I know there are plenty of answers to this already. SO Question1, SO Question2, Every Other SO Question. I just couldn't find "using ../" as a relative import rather than the explicit path.
- I know that as of Python 2.5 they supported "relative imports" as per the documentation that mentions the use of
from .. import *
but I am specifically trying to do animport MyModuleName
so I can be more explicit in the unittest and avoid mangling/collisions of names.
What I am doing (and it is working for me) is the following:
sys.path.append("../")
And then importing what I need from the parent directory.
- Yes, there is an __init__.py in the parent directory,
- No, my parent path is not part of the Python path or environment variable
- Why don't I just add the parent path to the
sys.path
? Because it's relative. If I am running from /home/workspace/MyModule/unittests/ and my module is under /home/workspace/MyModule/ I assumed adding /home/workspace/MyModule/ to the path won't necessarily be true if a coworker runs this on his machine under his own directory of /home/documents/MyModule.
My Question:
Is this Python-proper? If not, what's wrong with this. Is there a better way? Or is this truly an RTFM moment where the answer is in one of the 7+ SO questions I've already looked at? (I saw those all recommending the explicit path rather than the relative path approach I took).
Other useful information:
- Python 2.6
- Working in Linux but could just as easily jump over to Win.