开发者

__init__.py usage for directories in Python

开发者 https://www.devze.com 2023-02-26 21:21 出处:网络
I use __init__.py in my project with the following structure : project\\ project.py cfg.py __init__.py database\\

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
       __i开发者_Go百科nit__.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 ?


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.


Relative imports.

from .. import database.data


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消