1

Consider I have the following project structure:

+PROJECT
|  +models
|  |  =__init__.py
|  |  =client.py
|  |  =config.py
|
|  +tests
|  | =__init__.py
|  | =example.py
|  | =example_two.py
|
|  README.md
|  requirements.txt

When I try to import a class from client and a variable from config into example.py, like so:

from models.config import var 
from models.client import Class

I receive a ModuleNotFound Error for both import statements. I know this question has been asked plenty of times before but those solutions don't resolve my issue. I tried placing client and config in the same level as the test folder. However, I received the same issue. It would be great If someone can help me work through this issue.

  • 1
    From which folder are you running it? And what's the command? – Jacopofar Jul 13 '18 at 10:33
  • I'm running example.py from C:\user\documents\project\tests\ –  Jul 13 '18 at 11:00
  • Your test scripts will have to modify sys.path to insert the PROJECT folder. – Duncan Jul 13 '18 at 11:48
  • 1
    @Duncan I tried appending my project dir to the PATH but I still get the same error. I checked my path and the dir to the project folder is there. I really don't understand what I am doing wrong –  Jul 13 '18 at 11:51
  • Create `PROJECT/__init__.py` as well as adding it to the path. – Duncan Jul 13 '18 at 12:01

2 Answers2

0

You will need to do a relative import (PEP-328), but according to this guide, you can only go up until the level where you launched the script from, which is the tests directory in you case.

So you'll either have to add the model directory to the path, or add the source folder of your project to a .pth file in your site-packages as shown here

Maarten Fabré
  • 6,354
  • 1
  • 13
  • 32
  • 1
    I receive error when trying the relative import E0402: Attempted relative import beyond top-level package. –  Jul 13 '18 at 11:10
0

Three possibilities come to my mind:

  • The module just works for certain python versions (e.g. 3.5 but not 3.6).
  • The path where your module is currently located does not appear in sys.path.
  • The class you want to use must be specified while importing the module because it is not specified in the __init__.py of the module itself.

As far as I can tell, only the first option might cause your problem.
Nevertheless I would make a quick check with

import sys
sys.path

and in case that the correct path is really missing..

sys.path.append('PathToModule')
  • 1
    I appended my project dir to PATH but I still receive the same ModuleNotFound Error. It says in diffbot's repository that is was updated to work with python 3 here: https://github.com/diffbot/diffbot-python-client/pull/6. However I don't understand why his import sys statement to PATH resolves their issue and not mine. –  Jul 13 '18 at 11:24