1

I found some questions that are similar but did not quite solve my problem (e.g. PATH issue with pytest 'ImportError: No module named YadaYadaYada')

My project is structured as follows:

MyApp
 |
 +--MyApp
 |   |
 |   +--__init__.py
 |   +--app.py
 |   +--config.py
 |
 +--tests
     |
     +--__init__.py
     +--test_app.py

in my test_app.py I import app.py, which works just fine.

from MyApp import app

but within app.py I import config.py like this.

import config

With this setup I can run the app module, but pytest fails to import 'config' and raises:

ImportError: No module named 'config'

pytest succeeds when I change the import statement in app.py to:

from MyApp import config

However, an error is raised when I try to run the app:

ImportError: No module named 'MyApp'

From reading other questions I'm confident that there is something wrong with the PYTHONPATH, I just could not figure out how to fix this.

georg23
  • 53
  • 1
  • 7

1 Answers1

2

set the PYTHONPATH variable to root folder of your project and set all other paths relative to this

Within same folder you use

import module

If referring from other folder you use

from module import class

change the references in your project as above and it should be resolved

Priyank Mehta
  • 2,453
  • 2
  • 21
  • 32
  • Thanks for the suggestion! I still run into the same problem. I set the PYTHONPATH within my virtualenv to the root folder (following this [link](https://stackoverflow.com/questions/4757178/how-do-you-set-your-pythonpath-in-an-already-created-virtualenv)), but the result is the same. – georg23 Nov 25 '17 at 19:01
  • 1
    I found a solution that works but does not seem to be very elegant: I added `import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '..', 'MyApp'))` in test_app.py before importing 'app.py'. Is there a more elegant way? – georg23 Nov 25 '17 at 19:30