eval和列表解析的一处陷阱
>>> def f(): a=1 return [i+a for i in range(3)] >>> f() [1, 2, 3] >>> def f(): a=1 return [i+eval('a') for i in range(3)] >>> f() Traceback (most recent call last): File "<pyshell#13>", line 1, in <module> f() File "<pyshell#12>", line 3, in f return [i+eval('a') for i in range(3)] File "<pyshell#12>", line 3, in <listcomp> return [i+eval('a') for i in range(3)] File "<string>", line 1, in <module> NameError: name 'a' is not defined
看看locals()是什么:
>>> def f(): a=1 return [print(locals()) for i in range(3)] >>> f() {'i': 0, '.0': <range_iterator object at 0x0000000003353530>} {'i': 1, '.0': <range_iterator object at 0x0000000003353530>} {'i': 2, '.0': <range_iterator object at 0x0000000003353530>} [None, None, None] >>> def f(): a=1 return [(i+a,print(locals())) for i in range(3)] >>> f() {'a': 1, 'i': 0, '.0': <range_iterator object at 0x0000000003353530>} {'a': 1, 'i': 1, '.0': <range_iterator object at 0x0000000003353530>} {'a': 1, 'i': 2, '.0': <range_iterator object at 0x0000000003353530>} [(1, None), (2, None), (3, None)]