Lin Ma Lin Ma - 1 year ago 138
Python Question

python memorize default parameter value or not

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 y:
print x

if __name__ == "__main__":
foo(100, True) # print
foo(300) # not print


Answer Source

The default object is created once.

Maybe this example will simplify the explanation:

>>> import random
>>> def func(value=random.random()):
...     print value
>>> func()
>>> func()
>>> func(1)
>>> func()

The default value is an object which is created when the function is defined. In my case, the created object was random value 0.941870977323.

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 is it relevant?

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 False.

If the default is something that can change, it is important to understand that it is created only once:

  • in case of random: it is a random value, but always the same random value
  • in case of [] 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.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download