python eval忽略本地,并寻找全局

时间:2015-06-04 19:38:12

标签: python global-variables eval local-variables

当我在新的Python 3.4.1 shell窗口中运行此代码时:

>>> def golf(c):
 a,d=[],{"U":"a.append(int(x[5]))","O":'a.pop() if a else 0',"E":'a[-1]'}
 return sum(eval(d[x[1]])or 0 for x in c)or 0

>>> golf(("PUSH 3", "POP", "POP", "PUSH 4", "PEEK", "PUSH 9", "PUSH 0", "PEEK", "POP", "PUSH 1", "PEEK"))

即使我在第二行声明 a ,我也会收到此错误 - a,d = [],{.....

Traceback (most recent call last):
  File "<pyshell#25>", line 1, in <module>
    golf(("PUSH 3", "POP", "POP", "PUSH 4", "PEEK", "PUSH 9", "PUSH 0", "PEEK", "POP", "PUSH 1", "PEEK"))
  File "<pyshell#24>", line 3, in golf
    return sum(eval(d[x[1]])or 0 for x in c)or 0
  File "<pyshell#24>", line 3, in <genexpr>
    return sum(eval(d[x[1]])or 0 for x in c)or 0
  File "<string>", line 1, in <module>
NameError: name 'a' is not defined

(注意:如果我在shell中将 a 声明为空数组,则每次运行时都会更新 golf() 而不是在函数中重新声明为空。)

如果这不够奇怪,我可以通过从生成器中取出 eval() 来“解决”问题。像这样:

def golf(c):
 a,d=[],{"U":"a.append(int(x[5]))","O":'a.pop() if a else 0',"E":'a[-1]'}
 for x in c:
  print(eval(d[x[1]])or 0)
 return []

即使 a 仍然未定义(在shell窗口中),我得到:

0
3
0
0
4
0
0
0
0
0
1
[]

为什么 eval() 忽略我的本地 a

1 个答案:

答案 0 :(得分:0)

使用Python习语Default Parameter Values

def good_append(new_item, a_list=None):
    if a_list is None:
        a_list = []
    a_list.append(new_item)
    return a_list