I am developing a Python function of which the intermediate results should conditionally be accessible outside of the function, for plotting. It concerns > 20 variables of large size. To preserve memory I aim to only make the variables globally available in case the plotting is needed.
See the following code snippet I initially expected to work like desired:
def x():
if True:
global a
a = 10
return
x()
print(a)
Expected result: variable 'a' can be printed only if the if statement is executed.
Actual result: variable 'a' can always be printed.
I tried many things but cannot seem to achieve the desired behaviour. Proper programming would be to return the variables needed to the global scope, using 'return'. However, I do not know how to do that conditionally in a pretty way, with this many variables. Can anybody explain the behaviour I see, and suggest how to achieve the desired behaviour?
The determination of whether a variable is local or global is made when the function is being compiled, not when it runs. So this can't be dynamic.
You can solve it by using the locals()
and globals()
functions to access the different variable environments.
def x():
env = locals()
if <condition>:
env = globals()
env['a'] = 10
return
x()
print(a)