Why is this not working ?
u = {}
for me in ['foo', 'bar']:
def callback():
return 'I am %s' % me
u[me] = callback
The output I get is:
>>> u['foo']()
'I am bar'
It seems the callback
is defined once at the latest iteration.
EDIT
As proposed by kawadhiya21, a class approach would work:
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)
But it is far more complicated than the former approach.