2

I use __init__.py in my project with the following structure :

project\
    project.py
    cfg.py
    __init__.py

    database\
       data.py
       __init__.py

    test\
       test_project.py
       __init__.py

All is OK when I need to see database\ modules in project.py with

from database.data import *

But if I need to have some test code inside the test_project.py, how to 'see' the database\ modules ?

philnext
  • 3,242
  • 5
  • 39
  • 62

3 Answers3

4

You have 3 options:

  • use relative imports (from .. import database.data). I wouldn't recommend that one.
  • append paths to sys.path in your code.
  • use addsitedir() and .pth files. Here is how.
Community
  • 1
  • 1
vartec
  • 131,205
  • 36
  • 218
  • 244
2

Relative imports.

from .. import database.data
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
2

If you run a script from the directory that contains project\, you can simply do from project.database.data import *, in test_project.py.

This is generally a good idea, because relative imports are officially discouraged:

Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports. Even now that PEP 328 [7] is fully implemented in Python 2.5, its style of explicit relative imports is actively discouraged; absolute imports are more portable and usually more readable.

Absolute imports like the one given above are encouraged.

Eric O. Lebigot
  • 91,433
  • 48
  • 218
  • 260