I have the following structure in my project;
project
src
├── A.py
└── B.py
tests
├── test_b.py
and in B.py I import A.py like this;
from A import foo
B.py works fine when I run it. However when testing B.py in test_b.py I get an error saying
No module named A
I can make the test work with relative imports in B.py, but that fails when I run the module by itself.
Relative imports outside packages is a recipe for nightmares. Everything forks fine when you develop and test in the source directory. And problems start to occur as soon as you want to use your code from a different directory.
The workaround: Consistently add the directory of __file__
in sys.path
before your local imports. As sys.path
is a writable list, it will work. You should at least try to not add the directory if it is already present...
The idiomatic way: If you need local imports, then you probably need a package. It may require some work, because packages are expected to be installed , but it is a large + if you intend to later deploy your code. The downside, it that a package must be started as a module ( python -m xy
) and not as a plain script ( python x/y.py
). With your current structure, I would just add an empty __init__.py
file in both src
and tests
folder, and add a __main__.py
file in src if you want to lauch directly the package.
Then you should run everything (including tests and dev runs) from project: python -m src.B [params...]
. Same thing for the tests python -m tests.test_b
. Or directly (as the test folder and files start with test): python -m unittest discover
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.