title: Python - bound variable scope to closure
body: <p>I have some function which uses outside variables. A (substantially) simplified example:</p>
  <pre><code>a = 2
  b = 3
  
  def f(x):
      return x * a + b
  </code></pre>
  <p>While I need <code>a</code> and <code>b</code> in <code>f</code>, I don't need them anywhere else. In particular, one can write <code>a = 5</code>, and that will change the behavior of <code>f</code>. How should I make <code>a</code> and <code>b</code> invisible to the outside?</p>
  <p>Other languages allow me to write roughly the following code:</p>
  <pre><code>let f = 
     a = 2
     b = 3
     lambda x: x * a + b
  </code></pre>
  <p>What I want:</p>
  <ul>
  <li><code>f</code> must work as intended and have the same signature</li>
  <li><code>a</code> and <code>b</code> must be computed only once</li>
  <li><code>a</code> and <code>b</code> must not exist in the scope outside of <code>f</code></li>
  <li>Assignments <code>a = ...</code> and <code>b = ...</code> don't affect <code>f</code></li>
  <li>The cleanest way to do this. E.g. the following solution formally works, but it introduces <code>g</code> and then deletes it, which I don't like (e.g. there is a risk of overriding an existing <code>g</code> and I believe that it's simply ugly):</li>
  </ul>
  <pre><code>def g():
      a = 2
      b = 3
      return lambda x: x * a + b
  
  f = g()
  del g
  </code></pre>