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").
from .. import *
but I am specifically trying to do an import 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.
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:
We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.
Make an empty file called __init__.py in the same directory as the files. That will signify to Python that it's "ok to import from this directory". The same holds true if the files are in a subdirectory - put an __init__.py in the subdirectory as well, and then use regular import statements, with dot notation.
Relative imports use dot(.) notation to specify a location. A single dot specifies that the module is in the current directory, two dots indicate that the module is in its parent directory of the current location and three dots indicate that it is in the grandparent directory and so on.
Don't run the test from the tests folder. Run it from the root of your project, which is the module folder. You should very rarely need to muck with either sys.path
or PYTHONPATH
, and when you do, you're either causing bugs for other libraries down the road or making life harder on your users.
python -m TestsFolder.UnitTest1
If you use a test runner like py.test, you can just run py.test
from the root of your checkout and it'll find the tests for you. (Assuming you name your tests something more like test_unit1.py
. Your current naming scheme is a little unorthodox. ;))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With