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

2024-09-30 16:35:25 发布

您现在位置:Python中文网/ 问答频道 /正文

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

你知道吗垃圾邮件.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

你知道吗鸡蛋.py你知道吗

from spam import writeOtherGlobals
sausages = 5
writeOtherGlobals()
print sausages # I want this to print 10

Tags: theto函数frompy名称编辑空间
2条回答

您可以使用'dir(module)`方法,排除uuu变量(忽略名称等),或者您可能希望在模块末尾添加一个变量,如下所示:

#in module.py
a = ...
b = ...
# function/class definitions etc...
_globals = globals()

所以现在你可以

# in anothermodule.py
import module
print module._globals

所有的globals现在都已打印出来,您可以像在原始类中调用globals()一样访问每个globals。你知道吗

注意你不需要知道module.py的名字,只要你的模块有一个._globals它的名字就行了

def get_globals(module_py):
    print(module_py._globals)
import inspect

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

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

相关问题 更多 >