如何在Python中隐式传递当前的全局命名空间

时间:2017-05-03 19:26:33

标签: python python-2.7 global-variables

我想隐式地将当前全局命名空间的引用传递给函数,以便我可以编辑它。我觉得这是可能的,因为exec()做到了,但这可能太特殊了。

spam.py

# 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

2 个答案:

答案 0 :(得分:1)

import inspect

def get_globals():
    return inspect.stack(1)[1][0].f_globals

此函数将返回调用它的上下文的全局变量字典。

答案 1 :(得分:1)

您可以使用'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)