Question

I am still getting my head around the import statement. If I have 2 folders in the same level:

  1. src
  2. test

How to make the py files in test import the modules in src? Is there a better solution (like put a folder inside another?)

Was it helpful?

Solution

The code you want is for using src/module_name.py

from src import module_name 

and the root directory is on your PYTHONPATH e.g. you run from the root directory

Your directory structure is what I use but woth the model name instead from src. I got this structure from J Calderone's blog and similar to A google blog

OTHER TIPS

Try this out:

import sys
import os
sys.path.append(os.path.join('..', 'src'))
import module_in_src_folder

edited to support any platform

I have exactly the same situation as the OP with all the python projects I write:

  • Project Folder
    1. src
    2. test

All modules, whether in src, or test, or subfolders of these always use the form of import that Mark shows in his answer:

from src import module_name

What I have done is write a module that sits in Project Folder and recursively discovers all the test modules within the test folder and gets unittest to run all those tests. As python is running in Project Folder, then modules are relative to the working directory.

This means that the tests are just like any other client that wants to modules from src.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top