My goal is to change the scope of a function to a dictionary, instead of where it is defined, so that the function sees the variables in the dictionary.
I found out I was able to do the following:
my_dict = {'x': 1, 'y': 2}
def add_all():
x + y + z
# reference the functions in the dictionary
my_dict.update({'add_all': add_all})
# append my_dict to __global__ of the function
my_dict['add_all'].__globals__.update(my_dict)
z = 3
my_dict['add_all']() # sees x, y and z
# 6
This works, now I try to make another function that changes the variables in the enclosing scope.
def update_x_y(x, y):
# Have to explicitly refer to my_dict here
my_dict.update({'x': x, 'y': y})
# Must update the __globals__ of add_all() again
add_all.__globals__.update(my_dict)
add_all()
my_dict.update({'update_x_y': update_x_y})
my_dict['update_x_y'].__globals__.update(my_dict)
my_dict['update_x_y'](10, 20)
# 33
This also works, but very inelegant and dangerous.
Questions:
It looks like
__globals__
is a dictionary in which a function will evaluate; What I'm doing with__globals__.update()
is merely giving it some new values, so each time something changes inmy_dict
, I have to update again.- Is there a way that I could supplant
__globals__
withmy_dict
, albeitreadonly
?
- Is there a way that I could supplant
In the
update_x_y()
function, I had to explicitly refer tomy_dict
which is defined in the global scope.- Is there a way in functions to refer to variables in the outer scope?
nonlocal
cannot be used, because the enclosing scope has to be a closure