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

时间:2014-07-07 16:26:51

标签: python python-3.x flask global-variables

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

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

所以我的递归函数看起来像这样:

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)

我正在使用烧瓶,但我认为不是那么相关。

1 个答案:

答案 0 :(得分:1)

你是changing a name, not mutating a reference

# 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