Python eval忽略局部变量,寻找全局变量



当我在一个新的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
[]

<为什么strong> eval () 无视当地 ?

使用Python成语默认参数值:

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

相关内容

  • 没有找到相关文章

最新更新