title: How to import modules in python using importlib?
body: <p>I have this project structure:</p>
  <blockquote>
  <p>Scripts</p>
  <pre><code>-- A
      == AA
          ++ __init__.py
          ++ AAA.py
          ++ AAB.py
          ++ AAC.py
      == AB
          ++ __init__.py
          ++ ABA.py
          ++ ABB.py
          ++ ABC.py
  -- B
      == BA
          ++ __init__.py
          ++ BAA.py
          ++ BAB.py
          ++ BAC.py
      == BB
          ++ __init__.py
          ++ BBA.py
          ++ BBB.py
          ++ BBC.py
  </code></pre>
  </blockquote>
  <p>I want to import classes inside <code>Scripts/A/AA/AAA.py</code> into <code>Scripts/B/BB/BBC.py</code>. I have used some solutions:</p>
  <ol>
  <li><code>from AAA import *</code> gives me <code>ImportError: No module named AAA</code>.</li>
  <li><code>from Scripts.A.AA.AAA import *</code> gives me <code>ImportError: No module named Scripts.A.AA.AAA</code>.</li>
  <li><code>from ..A.AA.AAA import *</code> gives me <code>ValueError: Attempted relative import beyond toplevel package</code>.</li>
  <li><code>from ....A.AA.AAA import *</code> gives me <code>ValueError: Attempted relative import in non-package</code>.</li>
  </ol>
  <p>what should I do ?</p>
  <p><strong>EDIT 1:</strong></p>
  <p>I have changed the project's structure and now it's something like this:</p>
  <blockquote>
  <p>Scripts</p>
  <pre><code>-- elements
      == A
          ++ __init__.py
          ++ AAA.py
          ++ AAB.py
          ++ AAC.py
      == B
          ++ __init__.py
          ++ BAA.py
          ++ BAB.py
          ++ BAC.py
  -- general
      == imports.py
      == __init__.py
  -- main.py
  </code></pre>
  </blockquote>
  <p>I have wrote this piece of code to import all classes:</p>
  <pre><code>elementDict = []
  dirList = os.walk('elements') 
  for dname in dirList:  
      fileList = dname[2]
      for fname in fileList:
          if fname != '__init__.py' and fname.endswith('.py') and (not fname.endswith('_ut.py')) and (not fname.endswith('~')):  
              path = dname[0].split(os.sep)
              path = filter(None, path[path.index('elements'):])
              dir = '.'.join(path)
              mod = importlib.import_module(dir + '.' + fname[:-3])
              for cname, obj in inspect.getmembers(mod, inspect.isclass): 
                  if cname not in elementDict:  
                      elementDict[cname] = obj
  </code></pre>
  <p>This results in:</p>
  <pre><code>Traceback (most recent call last):
    File &quot;C:\Users\test\Scripts\general\imports.py&quot;, line 29, in __init__
      mod = importlib.import_module(dir + '.' + fname[:-3])
    File &quot;C:\Python27\lib\importlib\__init__.py&quot;, line 37, in import_module
      __import__(name)
  ImportError: No module named elements.A.AAA
  </code></pre>
  <p>Any idea?</p>
  <p><strong>EDIT 2:</strong></p>
  <p>I have resolved the problem; I did not have any <code>__init__.py</code> in <code>elements</code>.</p>