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?

Community
  • 1
  • 1
serverpunk
  • 10,665
  • 15
  • 61
  • 95

3 Answers3

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.

proycon
  • 495
  • 3
  • 9
  • 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. – serverpunk Sep 25 '15 at 22:08
  • 1
    Does ``tests/`` have an ``__init__.py`` as well? I now notice it was missing in your listing. – proycon Sep 25 '15 at 22:10
  • Although I kinda promised no messing with paths, the parent of your project directory should be in your ``$PYTHONPATH`` (or ``sys.path.insert()``it) – proycon Sep 25 '15 at 22:15
1

Adding the sibling directory to sys.path should work:

import sys, os
sys.path.insert(0, os.path.abspath('../models'))
import my_model
pommicket
  • 929
  • 7
  • 17
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
    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. – serverpunk Sep 29 '15 at 12:56