From this blog, it seems Python memorize default parameter value during each function call.
But I tested and it seems not? For example, the 2nd function call does not print value of x, y is still False other than memorized value?
def foo(x, y=False):
if __name__ == "__main__":
foo(100, True) # print
foo(300) # not print
The default object is created once.
Maybe this example will simplify the explanation:
>>> import random >>> >>> def func(value=random.random()): ... print value ... >>> >>> func() 0.941870977323 >>> func() 0.941870977323 >>> func(1) 1 >>> func() 0.941870977323 >>>
The default value is an object which is created when the function is defined. In my case, the created object was random value
Every time the function is called without arguments, the same default value is used.
When it is called with an argument, then the defaut value is not used.
When the default is
False, it does not matter, because
False is immutable, so it does not matter whether it is an old
Falseor a new
If the default is something that can change, it is important to understand that it is created only once:
an empty list is created once, but if it is modified by adding elements, the next call will not create a new empty list - it will use the same one.