title: Doing recursive lookup of a variable
body: <p>I have a list of dictionaries to emulate a stack of environments for an interpreter. For example, in the first environment I might have the value <code>a=4</code> defined, and in the second environment I might have <code>b=3</code> defined, and so If I do <code>env_get(a) + env_get(b)</code> I should get <code>7</code>.</p>
  <p>Here is what I currently have for this:</p>
  <pre><code>def env_get(self, k, env=None):
      v = None
      for env in reversed(self.envs): # as the &quot;pop&quot; is the equivalent of env[-1]
          v = env.get(k)
          if v: break
      if not v: raise AttributeError(&quot;Env does not contain '%s'&quot; % k)
      return v
  </code></pre>
  <p>I was wondering if this could be condensed into a single recursive def such as the following:</p>
  <pre><code>envs=[{'a':4},{'b':3}]
  def get_env_recursive(k, env_stack=None):
      if not env_stack: raise AttributeError(&quot;Env does not contain '%s'&quot; % k)
      return env_stack[-1].get(k) or get_env_recursive(k, env_stack[:-1])
  </code></pre>
  <pre><code>&gt;&gt;&gt; get_env_recursive('a',envs)+get_env_recursive('b',envs)
  7
  </code></pre>
  <p>Or to go crazy on a one-liner could do something like:</p>
  <pre><code>&gt;&gt;&gt; getr=lambda k,env_stack: env_stack[-1].get(k) or getr(k, env_stack[:-1]) if len(env_stack)&gt;1 else env_stack[0][k]
  &gt;&gt;&gt; getr('a',envs)+getr('b',envs)
  # 7
  </code></pre>
  <p>Is there a better way I could do the above pattern?</p>