title: Python: Dynamic "from" import
body: <p>So i'm trying to turn a bunch of "from x import x" statements, that look like this:</p>
  
  <pre><code>from class_foo import class_foo
  </code></pre>
  
  <p>into something dynamic.  I'm trying to pass a path to a directory and have it import all of the modules therein.</p>
  
  <pre><code>def dynamicImport(dirPath):
      filez = os.listdir(dirPath)
      for file in filez:
          if "class" in file:
              oname = file[:-3] #cut off the file extension, trivial
  
              imp_statement = "from " + oname + " import " + oname
              #when I print imp_statement, I can verify it's being concatenated correctly
  
              exec(imp_statement)
  </code></pre>
  
  <p>When I run this function and pass it a path, the statement strings are being created properly and it <strong>produces no errors</strong>, yet then later I'll try to access one of the imported objects, and this happens:</p>
  
  <pre><code>foo = class_foo()
  
  NameError: name 'class_foo' is not defined
  </code></pre>
  
  <p>Clearly I'm doing something wrong. Any help would be appreciated.</p>