Rohit
Rohit

Reputation: 3146

Can't import package from parallel directory

I have 3 folders in my project: scripts , src, tests. In scripts, I have a script to populate my local db with test data (populate_db.py). In the tests folder, I have a file called generators.py, which I'm trying to import into populate_db.py , but I'm not having any luck. I have this:

code_path = Path("../")
sys.path.append(code_path / "tests")
from generators import UserFactory

but I get the error ModuleNotFoundError: No module named 'generators'. Strange thing, is I do

sys.path.append(code_path / "src")
from users.models import User

and that imports fine. Not sure what I've done differently/wrong. I also tried a relative import: from ..generators import UserFactory, but got attempted relative import with no known parent package. I do have __init__.py in the parent and tests directories (though there are no python files in the parent, only in the 3 children).

Upvotes: 1

Views: 293

Answers (2)

Rohit
Rohit

Reputation: 3146

I found that the correct way to add a path to sys.path when using the pathlib.Path is to convert it to a string:

sys.path.append(str(code_path / "tests"))

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71580

Try this:

from .tests.generators import UserFactory

Upvotes: 1

Related Questions