def func(arg1,arg2=[]):
var = arg2
var.append(arg1)
return var
func("hello")
print("case1 output --> ",func("world"))
def func2(arg1,arg2):
var = arg2
var.append(arg1)
return var
func2("hello",[])
print("case2 output --> ",func2("world",[])
This gives the output as -
case1 --> ['hello' , 'world']
case2 --> ['world']
First of all, this was a bit of shock to me according to my understanding from what I have come across about how formal and actual arguments, local variables and functions in python work. Now that I have seen the output in both the cases and have made the following assumptions.
Whenever a function is called, first of all there is an assignment operation as formal argument = actual argument which brings the formal argument in the local scope of the function. Case 1 is special because it has a default argument which is mutable. When the function is called for the first time, a list-type object gets mutated and returned. Now the function gets called second time, instead of reassignment of formal argument arg2 which will create a new empty list-type object, it mutates the same object which was mutated the last time. This means somehow, this function remembers the state of its default formal arguments which were mutated earlier. The same doesn't happen in case 2 where both are required arguments and hence it creates a new object each time the function is called. This seems odd at the first glance. But I am still not able to understand how this works exactly since this has completely changed my notion of how functions work in python at least as a beginner.
- Whatever my assumption is about this concept, is it correct and meaningful?
- Is there any specific reason why the function doesn't reassign arg2 = [ ] and create a new list object?
- Isn't a function supposed to forget the objects which only exist in its local scope ?
- Any detailed explanation of how this is exactly happening ? I would really like to know how the function is internally remembering the state of its formal argument even being present only in its local scope ?