[Python] Why do two Python dictionaries initiated by default parameter point to the same...

Discussão em 'Python' iniciado por Stack, Maio 29, 2025.

  1. Stack

    Stack Membro Participativo

    I am using Python 3.12 and wanted to initiate a dictionary with a passed value. If nothing was passed, an empty dictionary should be created in the outer dictionary.

    The following example:

    def result_dict[T](init: dict[str, T] = {}) -> dict[str, dict[str, T]]:
    return dict.fromkeys(["x", "y"], init)


    dict_1 = result_dict()
    dict_2 = result_dict()

    dict_1["x"]["one"] = "foo"
    dict_2["y"]["two"] = "bar"

    print("dict_1: ", dict_1)
    print("dict_2: ", dict_2)
    print("Is same?: ", dict_1 == dict_2)


    Output:

    dict_1: {'x': {'one': 'foo', 'two': 'bar'}, 'y': {'one': 'foo', 'two': 'bar'}}
    dict_2: {'x': {'one': 'foo', 'two': 'bar'}, 'y': {'one': 'foo', 'two': 'bar'}}
    Is same?: True


    I assume this is because the parameter to a dict is always a reference and therefore if you set it as the default parameter, the interpreter always takes the same default dict. As a developer, I would expect the default parameter to point to a new object.

    Is this a bug in python or expected behaviour?

    Continue reading...

Compartilhe esta Página