Consider the following example:
i=7
j=8
k=10
def test():
i=1
j=2
k=3
return dict((name,eval(name)) for name in [\'i\',\'j\',\'k\'])
>
This occurs because the generator expression has a different scope to the function:
>>> def test():
i, j, k = range(1, 4)
return dict((j, locals()) for _ in range(i))
>>> test()
{2: {'.0': , 'j': 2, '_': 0}}
Using j inside the scope binds it from the function, as that's the nearest enclosing scope, but i and k are not locally bound (as k isn't referenced and i is only used to create the range).
Note that you can avoid this issue with:
return dict(i=i, j=j, k=k)
or a dictionary literal:
return {'i': i, 'j': j, 'k': k}