title: Why do functions from a dynamically loaded module depend on where the module is stored?
body: <p>Following <a href="https://stackoverflow.com/questions/5362771/load-module-from-string-in-python/7548190#7548190">this answer</a>, I am using <code>imp.new_module</code> and <code>exec</code> to dynamically load a module and extract functions from it. However, when I store the module in a local variable, functions from it get broken. Here is an example:</p>
  
  <pre><code>import imp
  
  mod = None
  func = None
  
  code = """
  a = 42
  
  def func():
      print a
  """
  
  def main():
      #global mod
      global func
      mod = imp.new_module("modulename")
      exec code in mod.__dict__
      func = mod.func
  
  main()
  func()
  </code></pre>
  
  <p>Executing this with Python 2.7.3 yields <code>None</code>: <a href="http://codepad.org/geYhLJcd" rel="nofollow noreferrer">codepad</a>. After uncommenting <code>global mod</code> line, making <code>mod</code> global, the function works as expected and prints 42: <a href="http://codepad.org/wESS0m2e" rel="nofollow noreferrer">codepad</a>. </p>
  
  <p>What am I missing? Why does the behaviour change when module is stored in a local variable?</p>