title: subclassed python dictionary for custom namespace in exec() method
body: <p>I am trying to subclass a dictionary for use in an exec method.
  Ultimately, I would like the local function to have a custom name scoping behaviour.</p>
  
  <p>In the code below, function <code>b()</code> does in fact have the correct <code>globals()</code> dictionary available to it, however it fails to search it when resolving <code>z</code>.</p>
  
  <p>Does function <code>b()</code> first not search <code>locals()</code> then <code>globals()</code> ?</p>
  
  <p>Very puzzling.
  Any help appreciated.</p>
  
  <pre><code>t = '''
  def b():
  #   return (globals()['z']) #works
      return z #fails
  
  b()
  '''
  
  class MyDict(dict):
      def __init__(self, g):
          dict.__init__(self)
          self.my_g = g
  
  
      def __getitem__(self, key):
          print("GET ", key)
          try:
              val = dict.__getitem__(self, key)
          except:
              print("GET exception1")
              val = self.my_g[key]
          return val
  
  
  g = {'z':123}
  
  md = MyDict(g)
  
  #fails to find z
  exec(t, md, md)
  
  #works
  #exec(t, g, g)
  </code></pre>
  
  <h1>output</h1>
  
  <pre><code>GET  b
  Traceback (most recent call last):
    File "/project1/text12", line 31, in &lt;module&gt;
    File "&lt;string&gt;", line 6, in &lt;module&gt;
    File "&lt;string&gt;", line 4, in b
  NameError: global name 'z' is not defined
  </code></pre>