更改递归函数中的全局变量是否会更改顶层?



我有一个全局字典变量,我试图调用一个递归函数,根据它试图找到的键下降几个级别,然后改变该值。

我想知道为什么当我在函数中改变全局变量的分支时,它不改变全局变量。

我的递归函数是这样的

def update_dict_with_edits(base_system_dict, changed_json_dict):
    name = changed_json_dict["base_system"]["name"]
    if "base_system" not in base_system_dict:
        return
    sub_dict = base_system_dict["base_system"]
    if name == sub_dict["name"]:
        print(name)
        print("found it and updating")
        sub_dict = changed_json_dict
        # even if I print out here the_global_dict_object it is unaltered
        # print(the_global_dict_object)
        return
    if "sub_systems" not in sub_dict:
        return
    for d in sub_dict["sub_systems"]:
        update_dict_with_edits(d, changed_json_dict)

我在这里称之为:

@app.route('/test', methods=['GET', 'POST'])
def test():
    if request.method == 'POST':
        the_json = request.form.get('json_data', None)
        the_json = json.loads(the_json)
        update_dict_with_edits(the_global_dict_object, the_json)
        # here when I print out the_global_dict_object it is unaltered
        # print(the_global_dict_object)
        # but here when I render the variable the_json just to view it,
        # it is correctly edited but the change just doesn't happen in
        # the function
        return render_template('testing.html', the_json=the_json)

我用的是flask,但我不认为这是所有相关的

您正在更改名称,而不是更改引用:

# Assign a dict to the name `sub_dict`
sub_dict = base_system_dict["base_system"]
if name == sub_dict["name"]:
    # Update *that name* to point at a new dictionary
    sub_dict = changed_json_dict

改为更新base_system_dict中的引用:

if name == sub_dict["name"]:
    # Update *the reference* to point at a new dictionary
    base_system_dict["base_system"] = changed_json_dict

相关内容

  • 没有找到相关文章

最新更新