Tricky default mutable arguments


The default mutable arguments are created only at the function initialization time, not every time the function is called.
Look at the below example


def foo(data = []):

    'a demo Function'

    data.append("hai")

    print "Updated data: ",data

print "-----first call-------"

foo()

print "-----second call------"

foo() 
 


What we expect during first call? 
Output would be

-----first call-------
Updated data:  ['hai']

What happens in Second call?

-----second call------
Updated data:  ['hai', 'hai']

Oh no. how come?
Yes as I told before “default mutable arguments are created only at the function initialization time”
Since List is mutable when you call function foo() first time data will be initialized to [] and after “hai” is appended [“hai”].
During second call foo’s default argument will not be initialized again so data will be [“hai”, “hai”]

Python will bite if you don’t know it…

Why this design in python ?
Answer would be to get some speed and memory boosts.
By having immutable default arguments Python can construct them just once, instead for every function call.