4

I have a Python 3 project that's structured like this:

/project __init__.py /models __init__.py my_model.py base_model.py /tests __init__.py test.py 

In test.py I want to import my_model. My first attempt was from models import my_model, which threw an ImportError: No module named 'models'. This question recommended adding an __init__.py file to each directory, which didn't help. Another post said to modify the path with:

import sys; import os sys.path.insert(0, os.path.abspath('..')) 

but this throws an error when my_model tries to import from base_model.

This seems really straightforward but I'm stumped. Does anyone have any ideas?

3 Answers 3

1

Adding the sibling directory to sys.path should work:

import sys, os sys.path.insert(0, os.path.abspath('../models')) import my_model 
Sign up to request clarification or add additional context in comments.

Comments

1

Use absolute imports everywhere: from project.models import my_model, should work fine from wherever in your project, no need to mess with paths either.

3 Comments

I'm still getting the same ImportError when I import from project.models. I triple-checked that the root folder has __init__.py and everything.
Does tests/ have an __init__.py as well? I now notice it was missing in your listing.
Although I kinda promised no messing with paths, the parent of your project directory should be in your $PYTHONPATH (or sys.path.insert()it)
1

The answer depends on how you launch test.py. The only way I know to do relative imports is to have the file in a package. For the Python interpreter to know you're in a package is to import it in some way.

Use:

from ..models import my_model 

in test.py

And launch the Python Interpreter below the project folder.

You will then be able to import project.tests.test without error.

1 Comment

I'm launching test.py directly from the command line. When I try from ..models import my_model it gives me an error Parent module '' not loaded, cannot perform relative import. I made sure the root directory has an __init__.py file.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.