Reputation: 115
I know there are probably thousands of posts like this and i nearly read them all and still i could not fix my issue.
I have the following project structure:
project
│
├── main.py
├── module1
│ ├── __init__.py
│ ├── b.py
│ └── c.py
│
├── tests
│ └── tests_module1.py
in tests_module1.py i want to import functions b.py and c.py to test their functionality. I already tried the following imports:
I also tried adding init.py files to the project as well as the test folder with no succsess. It only works when i move the test_module1.py into the project folder and import with :
I am using Python 3.9
Upvotes: 1
Views: 1752
Reputation: 4218
See this post.
Python does not know the package structure if you run python3 tests_module1.py
from within the tests
directory.
Try the following b.py
:
# module1/b.py
def hello():
print("Hello world!")
Import it in tests_module1.py
:
from module1 import b
b.hello()
Run it from the project
directory with the -m
(run as module) switch:
python3 -m tests.tests_module1
Upvotes: 1
Reputation: 1033
Have a look at modifying the python search path: https://docs.python.org/3.9/install/index.html#modifying-python-s-search-path
Modifying Python’s Search Path
When the Python interpreter executes an
import
statement, it searches for both Python code and extension modules along a search path. A default value for the path is configured into the Python binary when the interpreter is built. You can determine the path by importing thesys
module and printing the value ofsys.path
...The expected convention for locally installed packages is to put them in the
…/site-packages/ directory
, but you may want to install Python modules into some arbitrary directory... There are several different ways to add the directory.The most convenient way is to add a path configuration file to a directory that’s already on Python’s path, usually to the
.../site-packages/
directory. Path configuration files have an extension of.pth
, and each line must contain a single path that will be appended tosys.path
...<<snip several other options>>
Finally, sys.path is just a regular Python list, so any Python application can modify it by adding or removing entries.
See also
Upvotes: 0
Reputation: 151
instead of from .. import b
you must try
from ...module1 import *
Upvotes: 0