最近用到了python的动态变量. 遇到的问题和一些使用方法记录一下.
在全局作用域中, locals()和globals()代表同一个全局作用域字典变量, 因此在全局作用域使用locals()和globals()增加变量效果是一样的:
>>> if globals() == locals():
... print 'yes'
...
yes
>>> lc = locals()
>>> lc['hi'] = 'hello'
>>> hi
'hello'
>>>
这个也没什么争议, 网上搜索很多, 问题就出在locals()做为函数或者类的局部作用域时:
>>> def test():
... lc = locals()
... lc['aa'] = 'world'
... print aa
...
>>> test()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in test
NameError: global name 'aa' is not defined
>>>
>>> def test1():
... print locals()
... lc = locals()
... lc['aa'] = 'world'
... print locals()
...
>>> test1()
{}
{'aa': 'world', 'lc': {...}}aa' is not defined
>>>
函数test() 报错为没有找到全局变量'aa', 而函数test1()可以看到使用locals()返回的字典变量可以给局部作用域添加变量, 所以网上说的locals()是只读的说法不正确, 另外一个证明locals()只读不正确的示例如下:
>>> def test():
... lc = locals()
... lc['bb'] = 'hello world'
... print bb
...
>>> test()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in test
NameError: global name 'bb' is not defined
>>> def test1():
... print locals()
... lc = locals()
... lc['bb'] = 'hello world'
... exec("print bb")
...
>>> test1()
{}
hello world
这里很明显, 使用exec()是可以找到这个通过locals()创建的局部变量, 这种方法在python35也是可以的.