Why are default values shared between objects?

Technology CommunityCategory: PythonWhy are default values shared between objects?
VietMX Staff asked 3 years ago

It is often expected that a function call creates new objects for default values. This is not what happens. Default values are created exactly once, when the function is defined. If that object is changed, like the dictionary in this example, subsequent calls to the function will refer to this changed object.

Consider:

def foo(mydict={}):  # Danger: shared reference to one dict for all calls
    ... compute something ...
    mydict[key] = value
    return mydict

The first time you call this function, mydict contains a single item. The second time, mydict contains two items because when foo()begins executing, mydict starts out with an item already in it.