Where does python store an imported function's global scope variables?

Viewed 406

I'm study python scope today and did some experiments. And I found an interesting phenomenon. That by calling exec("global var; var = value") inside an imported function. I can store this value in somewhere unknown. And later on I can retrieve it by using import module; print(module.var). Please see the code below:

# 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

I did a shallow copy of script.py's globals() before and after using str_to_global_var function(deepcopy will fail). They are comparing equal after remove 2 irrelevant identifier "new_global" and "cur_global", so it is said at the shallow copy level, the interpreter thought nothing changed in script.py's global scope after using the imported str_to_global_var function, as we all know it only updates a global variable to temp.py's scope.

But the question is, before we using import temp.py; print(temp.var) statement.
Where did python stored this temp.var's value?
How could I access it?
And If I want to make the imported str_to_global_var function to update globals for script.py, is there a trick to modify its attribute so that python will recognize it as a function of script.py?

2 Answers
Related