【发布时间】:2020-10-14 00:34:06
【问题描述】:
我的目标是将函数的范围更改为字典,而不是定义它的位置,以便函数看到字典中的变量。
我发现我能够做到以下几点:
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
这可行,现在我尝试创建另一个函数来更改封闭范围内的变量。
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
这也有效,但非常不优雅和危险。
问题:
-
看起来
__globals__是一个函数将在其中求值的字典;我对__globals__.update()所做的只是给它一些新值,所以每次my_dict发生变化时,我都必须再次更新。- 有没有办法可以用
my_dict代替__globals__,尽管是readonly?
- 有没有办法可以用
-
在
update_x_y()函数中,我必须明确引用在全局范围内定义的my_dict。- 函数中有没有办法引用外部作用域中的变量?
-
nonlocal不能使用,因为封闭范围必须是闭包
【问题讨论】:
-
你能提供更多关于你的目标的背景信息吗?这闻起来像 XY 问题
-
嗨@Chris_Rands,我只是想使用
my_dict作为两个函数的封闭范围来评估。