scope of eval function in python

后端 未结 2 1427
失恋的感觉
失恋的感觉 2021-01-01 13:52

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\'])
         


        
2条回答
  •  一向
    一向 (楼主)
    2021-01-01 14:41

    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}
    

提交回复
热议问题