0

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
Deffa
  • 159
  • 6
  • "It seems like python reuses the empty dictionary here: `child = {}`." - yup. This is a design mistake I haven't seen in any other language's default argument system. – user2357112 Nov 27 '21 at 07:35

0 Answers0