title: Python: weird "NameError: name ... is not defined" in an 'exec' environment
body: <p>I was confident to have at least some basic understanding of Python's scope system. Now I get an error and unfortunately I'm not even able to write a good code snippet for reproduction so far. I tried to reproduce it in a new small project, but everything works as I expect there :-/</p>
  
  <p>I can only describe what I do and hopefully somebody detects a pattern and can tell me what possibly goes wrong here.</p>
  
  <p>At first there is a python file <code>x.py</code> which implements a class <code>X</code>.</p>
  
  <p>In some other python file, there is the following string:</p>
  
  <pre><code>code="""
  ...
  from x import X
  ...
  class Y(X): # does not crash here, ...
      def __init__(self):
          X.__init__(self) # ... but here
          ...
  foo=Y()
  """
  </code></pre>
  
  <p>You can assume that python is able to find the <code>x</code> module. At some place, I try to execute that:</p>
  
  <pre><code>exec(code, globals(), locals())
  </code></pre>
  
  <p>And now I get the <code>NameError</code>. It tells me that <code>X</code> is not defined when it tries to call it's constructor. It was obviously defined a few lines above.</p>
  
  <p>If I modify <code>Y.__init__</code> with adding <code>from x import X</code> as first line, it works. But why the hell do I have to import it again there?</p>
  
  <p>As already indicated, the actual code is more complex and does more things. In an unlucky case, my posting does not even show the part which actually leads to the problem. But maybe you have some general ideas, how one can get such a behaviour.</p>