在Python中添加到本地命名空间? [英] Adding to local namespace in Python?
问题描述
有没有办法在Python中通过调用一个没有在本地明确赋值变量的函数来添加到locals的名字空间?
例如下面的例子当然不工作,因为locals()返回一个本地名称空间的副本),其中print语句将打印'1'。
def A():
,您可以通过使用
B(local())
print x
def B(d):
d ['x'] = 1
c>
解决方案*
exec''
启动函数来禁用Python编译器对本地变量访问执行的正常优化;这将使功能非常慢(我刚刚发布,今天早些时候,一个答案显示局部变量优化可以轻松地加速代码3或4倍),但它会使你想要的黑客工作。 Ie,在Python 2。*:def A():
exec''
B locals())
print x
def B(d):
d ['x'] = 1
如果您愿意,会发出
1
这个黑客在Python
3。*
(其中exec
只是一个函数,不是一个语句也不是一个关键字) - 编译器现在无条件地执行局部变量优化,所以不再有任何办法解决它,使这样的hack工作。Is there a way in Python to add to the locals name-space by calling a function without explicitly assigning variables locally?
Something like the following for example (which of course doesn't work, because locals() return a copy of the local name-space) where the print statement would print '1'.
def A(): B(locals()) print x def B(d): d['x'] = 1
解决方案In Python
2.*
, you can disable the normal optimizations performed by the Python compiler regarding local variable access by starting your function withexec ''
; this will make the function very much slower (I just posted, earlier today, an answer showing how the local-variable optimization can easily speed code up by 3 or 4 times), but it will make your desired hack work. I.e., in Python 2.*:def A(): exec '' B(locals()) print x def B(d): d['x'] = 1 A()
will emit
1
, as you desire.This hack was disabled in Python
3.*
(whereexec
is just a function, not a statement nor a keyword any more) -- the compiler now performs the local variable optimization unconditionally, so there is no longer any way to work around it and make such hacks work.这篇关于在Python中添加到本地命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!