The concept of default values in Python is based on using mutable or immutable objects. In programming practice, it is best not to use mutable objects as default values. Instead, use None as the default value to avoid problems. Immutable objects, such as numbers, strings, tuples, and None, do not change. For mutable objects such as dictionaries, lists, and class instances, changes can cause confusion.
Let's look at an example of a dictionary in a function and what's wrong with it and how to fix it.
We have a function. In this function, we have a dictionary as parameter and set the default value. The first time this function is called, mydict contains only one item. On the second call, mydict contains two items because when foo() started executing, mydict already had one item.
def foo(mydict={}): ... calculate... mydict[key] = value return mydict
We often expect function calls to create new objects with default values. However, it is not. Default values are only created once when the function is defined. If the object is modified, as in the dictionary example above, subsequent calls to the function will reference the modified object.
To solve the problem of using mutable objects as default values, like this -
def foo(mydict={}): ...
Use immutable objects, such as None -
def foo(mydict=None): if mydict is None: mydict = {}
When you have a function that is computationally expensive, one technique is to cache the argument and result values for each call to the function, and return the cached values when the same values are requested again.
This is called memoization and can be achieved like this -
# Callers can only provide two parameters and optionally pass _cache by keyword def expensive(arg1, arg2, *, _cache={}): if (arg1, arg2) in _cache: return _cache[(arg1, arg2)] # Calculate result = ... expensive computation ... _cache[(arg1, arg2)] = result return result
The following will store the results in the cache −
_cache[(arg1, arg2)] = result
The above is the detailed content of Why are default values shared between objects in Python?. For more information, please follow other related articles on the PHP Chinese website!