Why are default values shared between objects?

Default values are created by the def statement, not when the function is called. Consider this function:

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

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

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 (by executing the def statement). If that object is changed, like the dictionary in this example, subsequent calls to the function will refer to this changed object.

By definition, immutable objects such as numbers, strings, tuples, and None, are safe from change. Changes to mutable objects such as dictionaries, lists, and class in