Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

Why are default values sometimes shared between objects?

Default objects Shared values
0
10 Posted

Why are default values sometimes shared between objects?

0
10

It is often expected that a function CALL creates new objects for default values. This is not what happens. Default values are created when the function is DEFINED, that is, there is only one such object that all functions refer to. If that object is changed, subsequent calls to the function will refer to this changed object. By definition, immutable objects (like numbers, strings, tuples, None) are safe from change. Changes to mutable objects (like dictionaries, lists, class instances) is what causes the confusion. Because of this feature it is good programming practice not to use mutable objects as default values, but to introduce them in the function. Don’t write: def foo(dict={}): # XXX shared reference to one dict for all calls … but: def foo(dict=None): if dict is None: dict = {} # create a new dict for local namespace See page 182 of “Internet Programming with Python” for one discussion of this feature. Or see the top of page 144 or bottom of page 277 in “Programming Python” f

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.

Experts123