Why does the local default parameter p = []
not initialize its value despite being local scope for the call ()
function?
def call( p = []):
p += ['a']
return p
call()
Out[107]: ['a']
call()
Out[108]: ['a', 'a']
Why does the local default parameter p = []
not initialize its value despite being local scope for the call ()
function?
def call( p = []):
p += ['a']
return p
call()
Out[107]: ['a']
call()
Out[108]: ['a', 'a']
The default parameter object is created at function definition, not at every call.
Using mutable types as default parameter is a bad idea. The problem is that each default value is evaluated when the function is defined, i.e., usually when the module is loaded. and the default values become attributes of the function object. So if a default value is a mutable object, and you change it, the change will affect every future call of the function.
A better solution for this:
def call(p = None):
if p is None:
p = []
p += ['a']
return p