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?
The variables are needed outside of method or function calls or are shared within multiple functions globally are stored in Heap memory. # is allocated on heap.
A global variable is a variable which is accessible in multiple scopes. In Python, it is better to use a single module to hold all the global variables you want to use and whenever you want to use them, just import this module, and then you can modify that and it will be visible in other modules that do the same.
Global variables are stored in the data section. Unlike the stack, the data region does not grow or shrink — storage space for globals persists for the entire run of the program.
A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available from within any scope, global and local.
Here is an example of str_to_global that works on the calling module using sys._getframe:
#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)
cake
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With