Reputation: 83
my dir structure is like this
main/src/domain/entities.py
-entities.py has some classes
main/tests/test.py
in test.pt
I have from domain.entities import MyCLass
both tests and domain dir's have __init__.py
's.
It does not find the module i want though.
I run the test.py with python3 test.py
Any ideas why?
Upvotes: 3
Views: 173
Reputation: 106508
It's far easier to utilize sys.path, but if you want a solution that doesn't involve messing with the globals, then here it is.
__init__.py
file in the same folder as the module you want to import.from path.to.file.filename import MyClass
I tested this particular method moments ago. My folder hierarchy was one with a main.py
, and two nested folders domains/entities
. Each folder except for the uppermost level (i.e. the level that main.py
lives in) has an __init__.py
file in them.
Illustrated:
main.py
project/
__init__.py
domains/
__init__.py
entities/
__init__.py
module1.py
Upvotes: 0
Reputation: 725
You need __ini__.py
in every directory within the package
main/__init__.py
main/src/__init__.py
main/src/domain/__init__.py
main/src/domain/entities.py
main/tests/__init__.py
Upvotes: 1
Reputation: 1469
is main/src in sys.path? Python resolves module names by searching the directories in sys.path. For example "import ../module.py" is not valid. To fix your problem do something like this: In your "main/tests/test.py" file add:
import sys, os
sys.path.insert(0, os.path.abspath("../src") )
# Then try
from domain.entries import MyClass
You will also need to make sure that main/src/domain contains an init.py file. Also you don't need init.py in main/tests unless your going to add it's parent directory to your path and import tests.something.
Hope this helps.
Upvotes: 3