1

I have the following structure

abc/
    __init__.py
    settings.py
    tests/
       __init__.py
       test.py

in test.py, I am getting an ImportError for

#test.py
import abc.settings
yayu
  • 7,758
  • 17
  • 54
  • 86
  • 2
    You have to add the main directory (where `abc` is in), to your `sys.path` – Wolph Dec 15 '14 at 22:17
  • @BlackVegetable oh, so if I move tests folder to the same level as abc then it should work – yayu Dec 15 '14 at 22:18
  • My comment was slightly mistaken. Look to @Wolph for the correct answer. – BlackVegetable Dec 15 '14 at 22:18
  • If you feel like getting your hands dirty, you can try out this module: https://docs.python.org/2/library/imp.html – BlackVegetable Dec 15 '14 at 22:38
  • That seems like an odd arrangement for tests. See e.g. http://www.jeffknupp.com/blog/2013/08/16/open-sourcing-a-python-project-the-right-way/ for a handy guide to structuring a package. – jonrsharpe Dec 16 '14 at 15:08

2 Answers2

2

You have two ways.

Firstly, by setting the path variable

import os
import sys
sys.path.insert(0, <Complete path of abc>)

Or by using relative imports.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
  • I cannot mess with sys.path as the framework already does this. could you talk about the relative import method? I tried `from ..abc import settings` and ran it with `python -m` but I'm still getting an error – yayu Dec 15 '14 at 22:32
  • Refer [this](http://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python) – Bhargav Rao Dec 15 '14 at 22:46
1

The variable sys.path is a list of strings that determines the interpreter’s search path for modules. It is initialized to a default path taken from the environment variable PYTHONPATH, or from a built-in default if PYTHONPATH is not set. You can modify it using standard list operations:

you need to add your root directory to sys.path :

import sys
sys.path.append('path_of_root')

Aldo '..'+sys.path[0] can give you the path of abc directory !

Mazdak
  • 105,000
  • 18
  • 159
  • 188