title: How to define a function inside a loop
body: <p>Why is this not working ? </p>
  
  <pre><code>u = {}
  for me in ['foo', 'bar']:
     def callback():
         return 'I am %s' % me
     u[me] = callback
  </code></pre>
  
  <p>The output I get is:    </p>
  
  <pre><code>&gt;&gt;&gt; u['foo']()
  'I am bar'
  </code></pre>
  
  <p>It seems the <code>callback</code> is defined once at the latest iteration. </p>
  
  <p><strong>EDIT</strong> </p>
  
  <p>As proposed by kawadhiya21, a class approach would work: </p>
  
  <pre><code>class CallbackFactory():
      def __init__(self, me):
         self.me = me
  
      def __call__(self):
         return 'I am %s' % self.me
  
  u = {}
  for me in ['foo', 'bar']:
  
     u[me] = CallbackFactory(me)
  </code></pre>
  
  <p>But it is far more complicated than the former approach.</p>