I found weird behavior during debugging and I would like an explanation of why this happens.
This is a minimal example:
import json
def add_dic_to_dic(parent, key, child = {}):
parent[key] = child
return child
my_dict = {}
my_sub_dict = add_dic_to_dic(my_dict, "a")
my_sub_dict = add_dic_to_dic(my_sub_dict, "b")
print(json.dumps(my_dict))
Output: ValueError: Circular reference detected
Why does this happen?
It seems like python reuses the empty dictionary here: child = {}.
The following workaround works as expected:
def add_dic_to_dic(parent, key, child = None):
child = child or {}
parent[key] = child
return child