Welcome, guest | Sign In | My Account | Store | Cart

If you want do distribute different modules in separate packages but under the same top directory that may be a problem when importing those modules. Since Python 2.5 the "pkgutil", described in the Python documentation under chapter 29.3, solves this problem.

Python, 31 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
"""
Example directory structure:

/test_company_in.py
/folder1/
  /company_inc/
    __init__.py  <- Apply code here!
    /toola/
      __init__.py
      ...
/folder2/
  /company_inc/
    __init__.py  <- Apply code here!
    /toolb/
      __init__.py
      ...
"""

# /folder1/company_inc/toola/__init__.py
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)

# /folder2/company_inc/toolb/__init__.py
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__)

#/test_company_in.py
import sys
sys.path += ["folder1", "folder2"]
import company_inc.toola
import company_inc.toolb

Without the "pkgutil" patch the import of "company_inc.toolb" would fail, because once the package location is found, the traversal through the sys.path stops. See the original Python documentation of "pkgutil" for more informations.