递归函数中更改全局变量是否影响最顶层

2024-06-26 01:45:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个全局dictionary变量,我试图调用一个递归函数,该函数根据它要查找的键向下移动几个级别,然后更改该值。在

我想知道为什么当我在函数中改变全局变量的一个分支时它没有改变它。在

所以我的递归函数如下所示:

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)

我称之为:

^{pr2}$

我用的是烧瓶,但我觉得没那么重要。在


Tags: 函数nameinjsonbasereturnifwith
1条回答
网友
1楼 · 发布于 2024-06-26 01:45:00

您是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中的引用:

^{pr2}$

相关问题 更多 >