![](/img/trans.png)
[英]Python: how can I import the namespace of some object to current namespace?
[英]How can I implicitly pass the current global namespace in Python
我想隐式地将当前全局名称空间的引用传递给函数,以便我可以对其进行编辑。 我觉得这是可能的,因为exec()
做到了,但这在某些情况下可能太特殊了。
垃圾邮件
# This will fail because globals() grabs the spam.py globals
# I would like to to grab the globals from wherever it was called from
def writeOtherGlobals( implicitGlobals=globals() ):
print "Got sausages", implicitGlobals['sausages']
implicitGlobals['sausages'] = 10
eggs.py
from spam import writeOtherGlobals
sausages = 5
writeOtherGlobals()
print sausages # I want this to print 10
import inspect
def get_globals():
return inspect.stack(1)[1][0].f_globals
此函数将返回调用它的上下文的全局字典。
您可以使用'dir(module)`方法,并排除__变量(以忽略名称等),或者您可能想在模块末尾添加一个变量,如下所示:
#in module.py
a = ...
b = ...
# function/class definitions etc...
_globals = globals()
所以现在你可以做
# in anothermodule.py
import module
print module._globals
现在将打印所有全局变量,并且可以像在原始类中调用globals()一样访问每个全局变量。
注意,您不需要知道module.py
的名称即可工作,只要您的模块具有._globals
,无论它的名称是什么,即可以正常工作
def get_globals(module_py):
print(module_py._globals)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.