17

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?)

Jader Dias
  • 88,211
  • 155
  • 421
  • 625

3 Answers3

10

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 with the model name instead from src. I got this structure from J Calderone's blog and

mmmmmm
  • 32,227
  • 27
  • 88
  • 117
  • 1
    can packages(folders) have underscores in the middle of the name? – Jader Dias Feb 14 '10 at 20:24
  • 2
    Also, make sure that the src directory is a package, by adding a ``__init__.py`` file. – codeape Feb 14 '10 at 20:26
  • 1
    I was adding the src directory to the PYTHONPATH, instead of the ROOT path. – Jader Dias Feb 14 '10 at 20:31
  • An interesting behavior occurs when you add the `src` folder to the PYTHONPATH is that then the `import module_name` statement works without a `from src` – Jader Dias Feb 14 '10 at 20:32
  • Jader from your comment to the other answer are you running from the test directory? If so you will need to add the root directory to your PYTHONPATH – mmmmmm Feb 14 '10 at 20:32
  • 1
    Jader yes adding src to PYTHONPATH does work - but then you end up with many entries and make it difficult to manage. If you run from the root of your project you do not need to alter your environment – mmmmmm Feb 14 '10 at 20:36
  • 1
    You can have _ in folder names but it is not good style (see PEP8) I just used that to try to have self documenting code here. – mmmmmm Feb 14 '10 at 20:37
6

Try this out:

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

edited to support any platform

Vadikus
  • 1,041
  • 6
  • 5
0

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.

quamrana
  • 37,849
  • 12
  • 53
  • 71