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,142
  • 5
  • 36
  • 61

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
  • 125,354
  • 36
  • 211
  • 241
2

Relative imports.

from .. import database.data
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
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
  • 86,421
  • 44
  • 210
  • 254