使用exec()设置局部变量时出现奇怪的行为

时间:2017-12-12 13:36:48

标签: python-3.x

我在使用exec设置局部变量时遇到问题。 我知道从安全角度使用exec的缺点,但此代码在受控环境中运行。

def f(e):
    print("Locals before:", locals())
    exec(e)
    print("Locals after:", locals())

输出:

>>> f('A=3')
Locals before: {'e': 'A=3'}
Locals after: {'e': 'A=3', 'A': 3}

似乎已经设置了局部变量A.

我将f更改为打印A失败:

def f(e):
    print("Locals before:", locals())
    exec(e)
    print("Locals after:", locals())
    print("A=", A)

输出:

>>> f('A=3')
Locals before: {'e': 'A=3'}
Locals after: {'e': 'A=3', 'A': 3}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in f
NameError: name 'A' is not defined

然而这有效:

def f(e):
    print("Locals before:", locals())
    exec(e)
    print("Locals after:", locals())
    print("A=", eval('A'))

输出:

>>> f("A=3")
Locals before: {'e': 'A=3'}
Locals after: {'e': 'A=3', 'A': 3}
A= 3

我也注意到了这种奇怪的行为。

def f(e):
    print("Locals before:", locals())
    exec(e)
    print("Locals after:", locals())
    A=locals()['A']
    print("A=", A)

输出:

>>> f('A=3')
Locals before: {'e': 'A=3'}
Locals after: {'e': 'A=3'}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in f
KeyError: 'A'

现在A不在本地字典中。 有人对此有解释吗?

我正在使用Python 3.5

0 个答案:

没有答案