python在哪里存储导入函数的全局范围变量?

Zen*_*Zen 7 scope global-variables python-import python-3.x

我今天正在研究python范围并做了一些实验.我发现了一个有趣的现象.通过调用exec("global var; var = value")导入函数内部.我可以将这个值存储在未知的地方.后来我可以通过使用来检索它import module; print(module.var).请参阅以下代码:

# temp.py
def str_to_global_var(string, obj):
    command_1 = 'global %s; %s=%r' % (string, string, obj)
    exec(command_1)



# script.py
from copy import copy
from temp import str_to_global_var

cur_global = copy(globals())
str_to_global_var('x', 6)

new_global = globals()

print(set(new_global.keys()) - set(cur_global.keys()))

d2 = copy(new_global)
d1 = copy(cur_global)

del d2['cur_global']
del d2['new_global']

print('Compare d2==d1: ', d2 == d1)
print("'x' in new_global: ",'x' in new_global)

import temp
print("temp.x:", temp.x)



# Interpreter running result
>>> ipython3 script.py

{'new_global', 'cur_global'}
Compare d2==d1:  True
'x' in new_global:  False
temp.x: 6
Run Code Online (Sandbox Code Playgroud)

我在使用str_to_global_var函数之前和之后做了一个浅的script.py的globals()副本(deepcopy将失败).它们在删除2个无关标识符"new_global"和"cur_global"之后进行比较,所以在浅层复制级别,解释器认为在使用导入str_to_global_var函数后script.py的全局范围没有任何变化,因为我们都知道它只是将全局变量更新为temp.py的范围.

但问题是,在我们使用import temp.py; print(temp.var) 陈述之前.
python在哪里存储了这个temp.var值?
我怎么能访问它?
如果我想让导入的str_to_global_var函数更新为script.py的全局变量,是否有一个技巧来修改它的属性,以便python将它识别为script.py的函数?

Yoa*_*ner 7

以下是使用sys._getframe在调用模块上工作的str_to_global的示例:

#a.py
def str_to_global(name, value):
    sys._getframe(1).f_globals[name] = value

#b.py
from a import str_to_global
str_to_global('cheese', 'cake')
print(cheese)
Run Code Online (Sandbox Code Playgroud)

蛋糕